gpt4 book ai didi

java - ArrayList - 如果同一个对象我列出了精确的 2 次并且如果为 : append to "tempFinalFilterSearchList" 则计数

转载 作者:行者123 更新时间:2023-11-29 08:25:25 27 4
gpt4 key购买 nike

基本上,我正在尝试查看 Arraylist 以检查同一对象是否列出了 2 次 - 如果:附加到“tempFinalFilterSearchList”

我不允许使用 Hashmap(学校作业)。

更新 - 此代码现在实际工作...现在我只需要从“tempFinalFilterSearchList”中删除重复项

public List<Venue> filterToFinalSearchList()
{

for (int i=0; i < tempFilterSearchList.size(); i++)
{

int occurences=0;

for (int j = 0; j < tempFilterSearchList.size(); j++)
{

if (tempFilterSearchList.get(i).getVenueId() == tempFilterSearchList.get(j).getVenueId())
{
occurences++;
}

}

if (occurences == 2)
{
tempFinalFilterSearchList.add(tempFilterSearchList.get(i));
}
}
return tempFinalFilterSearchList;
}
  • 如果相同的 venueId 在“tempfilterSearchList”中列出了 2 次,则必须将对象添加到“tempFinalFilterSearchList”...

  • 现在已经尝试了几种不同的方法,但运气不佳 - 还可以在这里/谷歌搜索 - 有很多解决方案,但都带有我不允许使用的 Hashmap。

预先感谢您的任何建议。

最佳答案

首先请记住,在同一个列表的循环中使用删除函数是不安全的(除非使用迭代器)。我假设您有一个类,我们称它为 A,它具有属性 venueId。它看起来像这样 + 您想要的其他属性:

public class A {
private int venueId;

public A(int venueId) {
this.venueId = venueId;
}

public int getVenueId() {
return venueId;
}

public void setVenueId(int venueId) {
this.venueId = venueId;
}
}

1.创建一个函数来解析列表并计算具有相同venueId的对象重复自身的次数

public boolean doesVenueIdRepeatInList(int venueId, List<A> list) {
int timesRepeated = 0;

//Parse the list and count the number of items that have the same venueId
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getVenueId() == venueId) {
timesRepeated++;
}
}

//If the venueId repeats more than 3 times
if (timesRepeated >= 3) {
return true;
}
return false;
}

3. 现在开始实际执行您所要求的代码。我们将解析列表并识别重复超过 3 次的对象。如果它们重复超过 3 次,我们将不会将它们添加到新列表中

List<A> tempFilterSearchList = Arrays.asList(
new A(1),
new A(2),
new A(1),
new A(2),
new A(3),
new A(1),
new A(2)
);

//We will be using a new list to put the result in
//It's not safe to use the delete function inside a loop
List<A> filteredList = new ArrayList<>();

//Count the number an object repeats and if it repeats more than 3 times store it inside repeatedVenueIds
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int venueId = tempFilterSearchList.get(i).getVenueId();
boolean itRepeat3Times = doesVenueIdRepeatInList(venueId, tempFilterSearchList);

//If it doesn't repeat more than 3 times add it to the new list
if(!itRepeat3Times) {
filteredList.add(tempFilterSearchList.get(i));
}
}

您的结果在 filteredList

关于java - ArrayList - 如果同一个对象我列出了精确的 2 次并且如果为 : append to "tempFinalFilterSearchList" 则计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683800/

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