1

我正在尝试创建一个结构,其中将包含多个字符串值的列表,例如“0212”,并且我想要三个 ArrayList。第一个 ArrayList 将采用值“02”的第一部分,第二个将采用第二部分“1”,第三个将采用第三个值“2”。然后我希望能够遍历值列表,以便我可以更快地找到特定的值,因为多个值对于值的第一部分和第二部分将具有相同的值。然后我想将它链接到一个值匹配“0212”的对象。我希望有人理解我要解释的内容,如果有人可以帮助我,我将不胜感激。先感谢您。

这是我目前将字符串值与 ArrayList 中的 DataObject 地址值匹配的代码:

public void setUpValues()
{   
    String otherString = "4210";

    Iterator<DataObject> it = dataObjects.iterator();

    while(it.hasNext())
    {
        DataObject currentDataObject = it.next();
        if(currentDataObject.getAddress().equals(otherString))
        {
            System.out.println("IT WORKSSSSSS!");
            currentDataObject.setValue("AHHHHHHHHH");

            System.out.println("Data Object Address: " + currentDataObject.getAddress());
            System.out.println("Data Object Type: " + currentDataObject.getType());
            System.out.println("Data Object Value: " + currentDataObject.getValue());
            System.out.println("Data Object Range: " + currentDataObject.getRange());
        }
        else
        {

        }
    }   
}
4

1 回答 1

0

Since the values are so tightly defined (three sections, each represented by one byte), I think you can build a lightweight solution based on Map:

Map<Byte, ArrayList<Byte>> firstSegments;
Map<Byte, ArrayList<Byte>> secondSegments;
Map<Byte, FinalObject> thirdSegments;

where FinalObject is the fully assembled data type (e.g., Byte[3]). This provides efficient lookup by segment, but you'll need to iterate over the arrays to find the "next" group of segments to check. Roughly:

Byte[3] needle = ...;
Byte firstSeg = ...;
Byte secondSeg = ...;
Byte thirdSeg = ...;

for (Byte b1 : firstSegments.get(firstSeg)) {
    if (b1.equals(secondSeg)) {
        for (Byte b2 : secondSegments.get(b1)) {
            if (b2.equals(thirdSeg)) {
                return thirdSegments.get(b2); // found a match
            }
        }
    }
}

It's not clear from your question, but if you're trying to decide whether a given Byte segment is in one of the arrays and don't care about iterating over them, it would be cleaner and more efficient to use a Set<Byte> instead of ArrayList<Byte>. Set provides a fast contains() method for this purpose.

于 2013-10-04T13:29:48.920 回答