我对链表非常陌生,但目前我有一个对象的链表,并且不知道如何通过使用链表中的一个对象来调用另一个方法。
public Store() {
products.add(new Product("Whiteboard Marker", 85, 1.50));
products.add(new Product("Whiteboard Eraser", 45, 5.00));
products.add(new Product("Black Pen", 100, 1.50));
products.add(new Product("Red Pen", 100, 1.50));
products.add(new Product("Blue Pen", 100, 1.50));
}
这些是我当前在链接列表中的对象。
我有一个名为 Product 的类,具有 getName 函数。
public String getName() {
return this.name;
}
所以我想知道当调用函数 getName 时,它如何返回“Black Pen”
谢谢。
最佳答案
如果我理解正确的话,你有一个产品对象列表,其中有一个名称的 getter,你想要获取产品的名称,而它位于 Arraylist 中。根据这个假设我创建了一个虚拟人 person
和ArrayList
并调用product的getter并打印它。
如果您知道 ArrayList
中对象的位置然后很容易打印它,只需在ArrayList
中给出对象的索引即可。否则,如果您知道该人的某些独特属性,那么您可以使用 if
条件来过滤该属性。
我已经添加了这两个案例并将其包含在评论部分中。
class Person {
private String name;
private String location;
public Person(String name,String location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
public class Test {
public static void main(String[] args) {
List<Person> productList = new ArrayList<>();
productList.add(new Person("Amit","india"));
productList.add(new Person("A", "bangalore"));
// case 1 :- when you know the location of person in LL.
System.out.println(productList.get(0).getName());
// case 2:- when you know some unique peroperty of person and filtering on base of this.
for(Person product : productList){
if(product.getLocation().equalsIgnoreCase("india")){
System.out.println("name of person " + product.getName());
}
}
}
}
Output :-
Amit
name of person Amit
关于java - LinkedLists 尝试调用一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601833/