【问题标题】:Why cant we cast vector to set in java为什么我们不能将向量转换为在 java 中设置
【发布时间】:2015-08-04 15:12:24
【问题描述】:

在尝试将向量转换为 java 中的设置时。它抛出了一个异常

不能转换为向量来设置,而我们可以将向量转换为列表。

【问题讨论】:

    标签: java vector hashmap set hashset


    【解决方案1】:

    您只能转换为超类型或子类型。例如,您可以从Number 转换为Integer 或从Integer 转换为Number,但您不能将Vector 转换为Set

    您可以将Vector 转换为Set,如下所示:

    Set<Integer> set = new HashSet<Integer>(vector);
    

    请注意,无论如何您都应该使用ArrayList 而不是Vector

    【讨论】:

      【解决方案2】:

      投射垂直,而不是水平。在其他工作中,可以将引用转换为其超类型或子类型,例如

         A
         |
      +--+--+
      |     |
      B     B2
      |
      C
      
      class A{}
      class B extends A{}
      class C extends B{}
      class B2 extends A{
          void foo(){}
      }
      

      你有

      B b = new C();
      

      C c = (C)b;//fine since b really holds C instance
      A a = (A)b;//also OK since A interface is guaranteed to have proper implementation 
                 //inherited by B type (or even its subtype)
      

      但是

      B2 b2=(B2)b;//will not compile because there is a chance that object stored in 
                  //b will not provide implementation of interface of B2 type 
                  //like `foo` method
      

      因此,由于 Set 不是 Vector 的超级或子类型,因此您不能使用强制转换。

      【讨论】:

        【解决方案3】:

        因为Vector 没有扩展SetSetList是两个不同的接口,它们都扩展了Collection

        类比:Apple 和 Banana 都继承自 Fruit。 RedApple 可以施放为 Apple 或 Fruit,但不能施放为 Banana。

        你可以做类似的事情:

        Set<Object> set = new HashSet<>(vector);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-13
          • 2012-02-16
          • 1970-01-01
          • 2013-06-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多