2017-04-25 29 views
3

我很新的链接列表,但目前我有一个对象的链表,并失去了如何通过使用链表中的一个对象调用另一个方法。LinkedLists试图调用一个类

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时,它会返回“黑色笔”

谢谢。

+0

私人字符串名称,私人诠释股票,私人双重价格; – Dan

+0

你是否熟悉指针? – NonCreature0714

+0

不太熟悉指针,但现在不好看他们 – Dan

回答

3

如果我理解正确,你有一个产品对象列表,它有一个名字的getter,你想获得产品的名称,而它的存在于Arraylist中。根据这个假设,我创建了一个虚拟的personArrayList,并调用产品的获取并打印它。

如果您知道对象在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 
+0

使用'get(int)'在'LinkedList'上效率低下。如果需要通过索引进行访问,请使用'ArrayList'。 –

+0

@ P.J.Meisch,我同意但我不认为这是OP的问题,如果你注意到在我的代码中我只使用'ArrayList'。在答案中也修改linklist到arraylist。 –

1

你的情况,让“黑笔,”你可以这样写:

products.get(2).getName(); 
0

调用存储在LinkedList对象的方法,你必须得到从上榜对象。要采取链表的第一个元素

products.getFirst().getName(); 

采取链表的第一个元素

products.getLast().getName(); 

请注意,你可以从链表元素从第一或从上只能按顺序启动。