- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
基本上,我正在尝试查看 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/
基本上,我正在尝试查看 Arraylist 以检查同一对象是否列出了 2 次 - 如果:附加到“tempFinalFilterSearchList” 我不允许使用 Hashmap(学校作业)。 更新
我是一名优秀的程序员,十分优秀!