gpt4 book ai didi

java - ArrayList 与数组。为什么一个工作,一个不工作?

转载 作者:行者123 更新时间:2023-11-29 07:35:58 24 4
gpt4 key购买 nike

我一直在尝试将旧的分配从数组切换到 arraylist , 但无论出于何种原因,当我修改它以使用 arrayList 时,我的查找方法不起作用.. 似乎总是回来-1 .

这是一个大类的一部分,所以除非完全必要,否则我不想包含所有内容,但我确实包含了声明以防它们很重要:

public class Switch {
private SwitchEntry[] camTable;
private int numEntries;
private int maxEntries;

public Switch() {
camTable = new SwitchEntry[100]; // default value
numEntries = 0;
maxEntries = 100;
}

public Switch(int maxEntries) {
camTable = new SwitchEntry[maxEntries];
numEntries = 0;
this.maxEntries = maxEntries;
}

原文:

public int find (MACAddress source) {
int found = -1;
for (int i=0; i < numEntries; i++)
if (source.isEqual (camTable[i].getAddress())){
found = i;
break;
}
return found;
}

修改:

public int find (MACAddress source) {
int found = -1;
for (int i=0; i < numEntries; i++)
if (source.isEqual (camTable.get(i).getAddress())){
found = i;
break;
}
return found;
}

修改 numEntries 的地方以及将新条目添加到 arrayList 的地方:

public void processFrame(Frame inFrame) {
// first, add source MAC to camTable if not already there
if (find(inFrame.getSource()) == -1) {
if (numEntries >= maxEntries) {
System.out.println ("Error...camTable is full - cannot add " + inFrame.getSource());
} else {
camTable.add(new SwitchEntry(inFrame.getSource(), inFrame.getPort())); //PROBLEM LINE
System.out.println ("Adding " + inFrame.getSource() + " to camTable");
}
}

//process frame
int index = find(inFrame.getDestination());
if (index != -1){
System.out.print ("Sending frame with data " + inFrame.getData() + " from " + inFrame.getSource() + " to " + inFrame.getDestination());
System.out.println (" out port " + camTable.get(index).getPort() );
} else {
System.out.print ("Flooding frame with data " + inFrame.getData() + " from " + inFrame.getSource() + " to " + inFrame.getDestination());
System.out.println (" out all ports" );

}

}

解决方法:

camTable.add(numEntries++, new SwitchEntry(inFrame.getSource(),inFrame.getPort()));

最佳答案

试试这个

public int find (MACAddress source) {
int found = -1;
ArrayList<MACAddress> camTable = new ArrayList<MACAddress>();
ListIterator<MACAddress> itr = camTable.listIterator();
while(itr.hasNext()){
MACAddress tempAdd = itr.next();
if(source.getAddress().equals(tempAdd.getAddress())){
found = itr.nextIndex();
return found;
}
return found;
}

我假设您在 ArrayList 中存储了 MACAddress 的对象。在 if 条件下,我检查 source.getAddress 到 tempAdd.getAddress() 是否相同,然后它将重新调整 ArrayList 的索引。这里 ArrayList局部变量 但你可以创建一个 类变量

关于java - ArrayList 与数组。为什么一个工作,一个不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35715538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com