2016-07-08 120 views
-3

我有这段代码最后的目标是排序多个数组。 当我尝试访问我的颜色比较器上的“.color”时出现问题。 对不起,这个愚蠢的问题,但我是新的Android。构造函数的问题

我的构造函数:

import java.util.*; 
    public class ColorClothes { 

     public ColorClothes() // <------ method 
     { 

     } 

     public Clothes[] Initialize(Clothes[] item) { 
      Clothes firstry[] = new Clothes[4]; 


      System.out.println("Unsorted"); 

      for (int i = 0; i < item.length; i++) { 
       System.out.println(item[i].record + "  " + item[i].color + "  " + item[i].clothes); 
      } 

      System.out.println("\nSorted By Color\n"); 

      Arrays.sort(item, new ColorComparator()); 

      for (int i = 0; i < item.length; i++) { 
       System.out.println(item[i].record + "  " + item[i].color + "  " + item[i].clothes); 
      } 





      return item; 

     } 


     public class Clothes { 
      public int record; 
      public String color; 
      public String clothes; 
     } 
    } 

我ColorComparator:

import java.util.Comparator; 

class ColorComparator implements Comparator 
{ 
    public int compare(Object str1, Object str2) 
    { 
     String str1Color = ((ColorClothes)str1).color; 
     String str2Color = ((ColorClothes)str2).color; 

     return str1Color.compareTo(str2Color); 

    } 
} 

无法解析 “色” 这发生在我的ColorComparator。我做错了什么?

+0

'ColorClothes'没有'color'字段,而是'Clothes'类。 –

+2

“ColorClothes”的一个实例没有颜色。这听起来像你应该接受一个'Clothes'的实例来代替。我强烈建议,如果你是Java新手,你可以避免使用嵌套类型,因为它们会让你感到困惑。我还建议你了解泛型,以便你可以实现'Comparator '并避免公共领域。 –

+0

问题解决ty帮助我了解我的错误:) –

回答

0

你的颜色属性是在类Clothes但你铸造成ColorClothes((ColorClothes)str1).color

尝试:

((Clothes)str1).color 

PS:类公共属性是不是真正的面向对象编程

0

布没有得到解决。 试试这个:

String str1Color = ((ColorClothes.Clothes)str1).color; 

String str2Color = ((ColorClothes.Clothes)str2).color; 
+0

请编辑更多信息。仅限代码和“尝试这个”的答案是不鼓励的,因为它们不包含可搜索的内容,也不解释为什么有人应该“尝试这个”。 – abarisone