Java 当对象也在ArrayList中时,如何访问该对象的ArrayList属性?

Java 当对象也在ArrayList中时,如何访问该对象的ArrayList属性?,java,object,arraylist,attributes,Java,Object,Arraylist,Attributes,所以我在ArrayList中有几个对象。每个对象都有一个属性,该属性是ArrayList中的多个字符串。我试图将单独的ArrayList中的字符串与对象属性中的字符串进行比较。问题是-get方法不起作用。每次我尝试使用.get().getColor();,它告诉我这种方法并不存在 对于上下文,以下是主要的对象/阵列列表: //fav colors of the two people ArrayList list1 = new ArrayList(); list1.add("RED&qu

所以我在ArrayList中有几个对象。每个对象都有一个属性,该属性是ArrayList中的多个字符串。我试图将单独的ArrayList中的字符串与对象属性中的字符串进行比较。问题是-get方法不起作用。每次我尝试使用.get().getColor();,它告诉我这种方法并不存在

对于上下文,以下是主要的对象/阵列列表:

//fav colors of the two people
ArrayList list1 = new ArrayList();
list1.add("RED");
list1.add("BLUE");
list1.add("GREEN");
ArrayList list2 = new ArrayList();
list2.add("YELLOW");
list2.add("PURPLE");

//colors i will compare the people's fav colors to
ArrayList comparison = new ArrayList();
comparison.add("PURPLE");
comparison.add("RED");

Person p1 = new Person("Sarah", 45, list1);
Person p2 = new Person("Simone", 33, list2);

//ArrayList containing the people
ArrayList bioBook = new ArrayList();
bioBook.add(p1);
bioBook.add(p2);
以下是Person类以及get方法的属性:

private String name;
private int age;
private ArrayList favColors;

public ArrayList getColors(){
     return favColors;
}
这就是我试图做的。我想把那个人最喜欢的颜色存储到另一个ArrayList中,这样我就可以比较它们了。这让我感觉很复杂,它明确地告诉我bioBook.get(h).getColors().size()和bioBook.get(h).getColors(g)由于.getColors()方法而无法工作

ArrayList trySmthg=new ArrayList();
//循环遍历第一个ArrayList
对于(int h=0;h

我很抱歉,这是我第一次在这里发帖,我试图搜索相关指南,但没有找到任何内容。

您没有指定列表的类型,因此它们被推断为通用对象列表(
列表
),而不是人员列表(
列表
)。因此,编译器不知道使用
get()
检索的任何元素都是
Person
,因此不会显示
getColors()
方法

您应该使用其泛型类型参数声明列表,如下所示:

List<Person> list = new ArrayList<Person>();
List List=new ArrayList();
此赋值的右侧也可以简化为
new ArrayList()



大多数现代IDE都会告诉您这一点,所以除非您的IDE没有这样做,否则您应该确保注意编译器警告。通常情况下,它们会在错误出现之前捕获到很多错误。

尝试切换到以下内容:

ArrayList<Object> trySmthg = new ArrayList();

//loops through the first ArrayList
for(int h = 0; h < bioBook.getColors().size(); h++){ // get the fields where you have the 
                                                     //arrayList of arraList
    
          for(int g = 0; g < bioBook.getColors().get(h).size(); g++){
            tryingSmthg.add(bioBook.getColors().get(h).get(g));
          }  
}
ArrayList trySmthg=new ArrayList();
//循环遍历第一个ArrayList
对于(inth=0;h
您的数组列表没有类型。 例如,如果我有: ArrayList persons=新建ArrayList()
我将能够执行persons.get(1).getName()

Java默认将ArrayList成员视为对象。您可以将它们类型转换为Person对象,也可以定义进入ArrayList的对象类型

要指定
人员
类的数组列表,请执行以下操作:

ArrayList<Person> bioBook = new ArrayList<Person>();

你真的试过吗?您也没有在代码中定义类型……这不仅是在
数组列表
中循环的一种非常糟糕的方式,而且您还没有为
列表
定义类型。此外,这并没有回答OP提出的任何问题。基本上,这个问题与getColors方法有关,为什么它不起作用,我将重点放在这个问题上
ArrayList<Person> bioBook = new ArrayList<Person>();
Person person = (Person)(bioBook.get(h));
person.getColors(g);