簡體   English   中英

需要了解Java中LinkedList class的一些基礎知識

[英]Need to know some basics of LinkedList class in Java

package abc;

class DependencyDataCollection
{
    private int sNo;
    private String sessionID;
    private int noOfDependency;
    private int noOfRejection;
    private int totalValue;

    /** Creates a new instance of DependencyDataCollection */
    public DependencyDataCollection(int sNo, String sessionID, int noOfDependency, int noOfRejection, int totalValue)
    {
        this.sNo = sNo;
        this.sessionID = sessionID;
        this.noOfDependency = noOfDependency;
        this.noOfRejection = noOfRejection;
        this.totalValue = totalValue;
    }

    public int getSNo()
    {
        return sNo;
    }

    public String getSessionID()
    {
        return sessionID;
    }

    public int getNoOfDependency()
    {
        return noOfDependency;
    }

    public int getNoOfRejection()
    {
        return noOfRejection;
    }

    public int getTotalValue()
    {
        return totalValue;
    }
}

public class DependencyStack {

    LinkedList lList;

    /** Creates a new instance of DependencyStack */
    public DependencyStack()
    {
        lList = new LinkedList();
    }

    public void add(int sNo, String sessionID, int noOfDependency, int noOfRejection, int totalValue)
    {
        lList.add(new DependencyDataCollection(sNo,sessionID,noOfDependency,noOfRejection,totalValue));
    }

    public int size()
    {
        return lList.size();
    }

    public void show()
    {
        for(int i=0;i<lList.size();i++)
        {
            DependencyDataCollection ddc = (DependencyDataCollection)lList.get(i);
            System.out.println(ddc.getSNo()+"   "+ddc.getSessionID()+"   "+ddc.getNoOfDependency()+"     "+ddc.getNoOfRejection()+"      "+ddc.getTotalValue());
        }
    }

    public int returnIndexOfSession(String sessionID)
    {
        DependencyDataCollection ddc = null;
        for(int i=0;i<lList.size();i++)
        {
            ddc = (DependencyDataCollection)lList.get(i);
            if(ddc.getSessionID().equals(sessionID))
                break;
        }
        return ddc.getSNo();
    }

    public static void main(String args[])
    {
        DependencyStack ds = new DependencyStack();
        ds.add(1,"a",0,0,0);
        ds.add(2,"b",0,0,0);
        ds.show();

        //System.out.println(ds.returnIndexOfSession("a"));

//        DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0);
//        System.out.println(ds.indexOf(ddc));
    }
}

這是 java 中的一個簡單的鏈表程序,它使用來自 java.utilC ZEFE6407D8E604E76A2F2ED4F8EBC2CBB4C21A29DC40AB61DZ 的內置鏈表 class 鏈表用於存儲不同數量的數據,使用 DependencyDataCollection Class..

現在我的問題是

1)請評估這個程序,我是否尊重所有 java 概念,如私人成員訪問,我已經完成了等等。

2) 我在查找特定 session 的索引時遇到問題。

例如,節點 1 包含 1,"a",0,0,0......節點 2 包含 2,"b",0,0,0

現在我想找到包含“b”或“a”數據之一的節點的indexOf。 什么可能是最短的內置方法可以做到這一點,因為我已經制作了一個名為“public int returnIndexOfSession(String sessionID)”的 function,它使用了 for 循環,我發現這非常耗時.. 還有其他出路嗎? .

請評估和指導,因為我是 java 的新手。

這是我要做的更改,理由在評論中。

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;


class DependencyDataCollection
{
    // makte them fnal, then you hava an immutible object and your code is much safer.
    // in your case you had noset methods so it was safe, but always try to make things final.
    private final int sNo;
    private final String sessionID;
    private final int noOfDependency;
    private final int noOfRejection;
    private final int totalValue;

    public DependencyDataCollection(final int    sNo, 
                                    final String sessionID, 
                                    final int    noOfDependency, 
                                    final int    noOfRejection, 
                                    final int    totalValue)
    {
        this.sNo            = sNo;
        this.sessionID      = sessionID;
        this.noOfDependency = noOfDependency;
        this.noOfRejection  = noOfRejection;
        this.totalValue     = totalValue;
    }

    public int getSNo()
    {
        return sNo;
    }

    public String getSessionID()
    {
        return sessionID;
    }

    public int getNoOfDependency()
    {
        return noOfDependency;
    }

    public int getNoOfRejection()
    {
        return noOfRejection;
    }

    public int getTotalValue()
    {
        return totalValue;
    }
}

class DependencyStack
{
    // change the type to be as generic as poosible - List interface
    // added generics so you get compile time safety and don't use casts later on
    // renamed it to something meaningful
    private final List<DependencyDataCollection> dependencies;

    // use an ArrayList instead of a LinkedList, it'll be faster since you are not inserting/deleting
    // into the middle of the list
    {
        dependencies = new ArrayList<DependencyDataCollection>();
    }

    // your Stack shouldn't know how to make the collections... (in my opinion)
    public void add(final DependencyDataCollection ddc)
    {
        dependencies.add(ddc);
    }

    public int size()
    {
        return dependencies.size();
    }

    // the next 3 methods are just convenience since you don't know if someione
    // will want to write to a file or a writer instead of a stream
    public void show()
    {
        show(System.out);
    }

    public void show(final OutputStream out)
    {
        show(new OutputStreamWriter(out));
    }

    public void show(final Writer writer)
    {
        show(new PrintWriter(writer));
    }

    public void show(final PrintWriter writer)
    {
        // use the new for-each instead of the old style for loop
        // this also uses an iterator which is faster than calling get
        // (well on an ArrayList it probably is about the same, but a LinkedList it'll be faster)
        for(final DependencyDataCollection ddc : dependencies)
        {
            writer.println(ddc.getSNo()            + "   " +
                           ddc.getSessionID()      + "   " +
                           ddc.getNoOfDependency() + "   " +
                           ddc.getNoOfRejection()  + "   " +
                           ddc.getTotalValue());
        }
    }

    public int returnIndexOfSession(final String sessionID)
    {
        DependencyDataCollection foundDDC;
        final int                retVal;

        foundDDC = null;

        for(final DependencyDataCollection ddc : dependencies)
        {
            if(ddc.getSessionID().equals(sessionID))
            {
                foundDDC = ddc;
                break;
            }
        }

        // deal with the fact that you might have not found the item and it would be null.
        // this assumes -1 is an invalid session id
        if(foundDDC == null)
        {
            retVal = -1;
        }
        else
        {
            retVal = foundDDC.getSNo();
        }

        return (retVal);
    }

    public static void main(final String[] args)
    {
        DependencyStack ds = new DependencyStack();
        ds.add(new DependencyDataCollection(1,"a",0,0,0));
        ds.add(new DependencyDataCollection(1,"a",0,0,0));
        ds.show();

        //System.out.println(ds.returnIndexOfSession("a"));

//        DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0);
//        System.out.println(ds.indexOf(ddc));
    }
}

編輯:

這將加快查找(和刪除)。

class DependencyStack
{
    // A Map provides quick lookup
    private final Map<String, DependencyDataCollection> dependencies;

    // a LinkedHashMap allows for quick lookup, but iterates in the order they were added... if that matters for show.
    {
        dependencies = new LinkedHashMap<String, DependencyDataCollection>();
    }

    // your Stack shouldn't know how to make the collections... (in my opinion)
    public void add(final DependencyDataCollection ddc)
    {
        if(ddc == null)
        {
            throw new IllegalArgumentException("ddc cannot be null");
        }

        dependencies.put(ddc.getSessionID(), ddc);
    }

    public int size()
    {
        return dependencies.size();
    }

    // the next 3 methods are just convenience since you don't know if someione
    // will want to write to a file or a writer instead of a stream
    public void show()
    {
        show(System.out);
    }

    public void show(final OutputStream out)
    {
        show(new OutputStreamWriter(out));
    }

    public void show(final Writer writer)
    {
        show(new PrintWriter(writer));
    }

    public void show(final PrintWriter writer)
    {
        // use the new for-each instead of the old style for loop
        // this also uses an iterator which is faster than calling get
        // (well on an ArrayList it probably is about the same, but a LinkedList it'll be faster)
        for(final DependencyDataCollection ddc : dependencies.values())
        {
            writer.println(ddc.getSNo()            + "   " +
                           ddc.getSessionID()      + "   " +
                           ddc.getNoOfDependency() + "   " +
                           ddc.getNoOfRejection()  + "   " +
                           ddc.getTotalValue());
        }
    }

    public int returnIndexOfSession(final String sessionID)
    {
        final DependencyDataCollection ddc;
        final int                      retVal;

        if(sessionID == null)
        {
            throw new IllegalArgumentException("sessionID cannot be null");
        }

        // get it if it exists, this is much faster then looping through a list
        ddc = dependencies.get(sessionID);

        // deal with the fact that you might have not found the item and it would be null.
        // this assumes -1 is an invalid session id
        if(ddc == null)
        {
            retVal = -1;
        }
        else
        {
            retVal = ddc.getSNo();
        }

        return (retVal);
    }

    public static void main(final String[] args)
    {
        DependencyStack ds = new DependencyStack();
        ds.add(new DependencyDataCollection(1,"a",0,0,0));
        ds.add(new DependencyDataCollection(1,"a",0,0,0));
        ds.show();

        //System.out.println(ds.returnIndexOfSession("a"));

//        DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0);
//        System.out.println(ds.indexOf(ddc));
    }
}

突出的一件事是缺少 javadoc 樣式的注釋(來自http://en.wikipedia.org/wiki/Javadoc

/**
 * Validates a chess move. Use {@link #doMove(int, int, int, int)} to move a piece.
 * 
 * @param theFromFile file from which a piece is being moved
 * @param theFromRank rank from which a piece is being moved
 * @param theToFile   file to which a piece is being moved
 * @param theToRank   rank to which a piece is being moved
 * @return            true if the chess move is valid, otherwise false
 */

您想使用 generics:

List<DependencyDataCollection> lList;

此外,在您的變量定義中,您應該使用接口 List 而不是具體類型 (LinkedList)。

要使 indexOf 工作,您的元素類型 (DependencyDataCollection) 需要實現比較器以實現相等:

class DependencyDataCollection{

  @Override
  public boolean equals(Object o){
    ...
  }
}

然后,您可以使用 List 接口提供的內置 indexOf()。 然而,它將執行與您現在執行的相同類型的循環。 如果這太耗時(真的嗎?),那么您需要一個哈希支持列表或其他東西(在這種情況下,您還需要實現 hashCode())。

更新:它會做同樣的循環,但比你現在更有效。 不要通過索引訪問鏈接列表,它不是為此而構建的,使用 foreach 循環或迭代器(或 ArrayList):

    for(DependencyDataCollection d: iList){
    ... }

你有一個好的開始。 您可以進行的改進:

  • Generics。 您的鏈接列表可能是

    LinkedList < DependencyDataCollection > lList; 這使您可以進行類型檢查。

  • 您在此處看到您的鏈表不方便搜索 - 您必須檢查每個值,這既慢又笨重。 這就是人們使用哈希圖的原因。

  • 查找構建器模式以找到繞過一長串構造函數參數的方法。

1)為什么不使用 Generics:

LinkedList<DependencyDataCollection> lList;

2)那是LinkedList的缺點,你不妨使用HashMap或者其他數據結構

在最近版本的 Java 中,您可以使用generics這樣您就不必強制轉換調用lList.get(i)時產生的 object 。 例如:

LinkedList<DependencyDataCollection> lList = new LinkedList<DependencyDataCollection>();

...

DependencyDataCollection ddc = lList.get(0);

要獲取特定元素的索引,請手動遍歷列表。 對於列表范圍內的每個索引 i,獲取 DependencyDataCollection 並查看它是否具有您想要的屬性。 如果是,請保存索引。

LinkedList 在 java.util 中,可以保存任何類型的 class。 例如,我使用名為 Application 的 class。 所以在下面的代碼中,我只有一個應用程序列表。 然后我把一個應用程序放在列表中。 我還可以遍歷我的應用程序以對我的對象做任何我想做的事情。

        LinkedList<Application> app = new LinkedList<Application>();

            app.add(new Application("firefox"));

    Iterator<Application> iterable = app.iterator();
    while(iterable.hasNext()){
        Application eachapp = iterable.next();
    }

如果您需要找到帶有 indexOf 的 object,您可以在我的案例“應用程序”中覆蓋 object 的 equal 方法,因此如果相等,我聲明並應用它等於和其他應用程序,如果字段名稱相同,那么

app.indexOf(new Application("firefox")) 將返回我剛剛插入的應用程序的索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM