2017-04-25 28 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(); 

請注意,你可以從鏈表元素從第一或從上只能按順序啓動。