【问题标题】:How to check whether a value is already in an arraylist before inserting it in Java?java - 如何在将值插入Java之前检查一个值是否已经在arraylist中?
【发布时间】:2013-05-10 01:59:19
【问题描述】:

我想将值插入到列表中,但前提是这些值尚未包含在列表中。到目前为止,我的代码创建了一个无限循环,因为当我将值添加到列表中时,列表的大小也会增加,因此无法满足 for 循环的终止条件。这是一个更大程序的一部分,e 是一种扩展 Point 的对象。 注意: e 扩展点。 e 有一个值(除了它从 Point 继承的坐标)。 如果 List 为空,我会将 e 存储在列表中。列表的类型为 e。 如果 List 不为空,我检查列表中是否存在与我输入的 e 具有相同点位置的 e。我不检查 e 对象,而是检查 x 和 y 值是否匹配。 更新代码:

    List<e> listClosestFirst = new LinkedList<e>();  

    if (listClosestFirst.isEmpty()) {
        listClosestFirst.add(e);
    }
    else {

        for (int i = 0; i < listClosestFirst.size(); i++) {
            if ((e.getLocation()).equals((listClosestFirst.get(i)).getLocation())) {
                // do nothing, move on      
            } // end if

            else {
                listClosestFirst.add(e);
            }

        } // end for loop

    } // end else statement

System.out.println("Closest First Memory: " + listClosestFirst);

【问题讨论】:

  • 这可能会有所帮助...LinkedList#contains
  • 这和旅行商问题有关系吗?
  • 如果你更详细地解释你在做什么,我们也可以帮助你清理你的代码。或者提供代码示例来帮助您。
  • 这与旅行商问题没有任何关系。这是我的项目的摘要(我需要使用列表的部分): 1)我需要创建自己的类,它扩展类 Point 并且还有一个 int 值(除了位置)。这是e。 2) 我需要使用随机生成器来随机生成 e 类的 x 和 y 坐标。 e类被随机放置在一个坐标平面上。 3) 我再次随机生成 x 和 y 坐标。如果 x 和 y 坐标与之前生成的任何值匹配,我将对象 e 添加到列表中。 (续)
  • (...cont) 但是,如果生成坐标的 e 已经在列表中,那么我应该跳过它并继续前进。包含似乎对我不起作用,因为它会检查列表中是否已经存在对象。我不想检查对象,而是如果 x 和 y 坐标匹配,那么我想跳过它。所以,为了使用 Contains,我实际上必须传入 if (listClosestFirst.contains(e.getLocation())) { },我认为这不会起作用,因为需要传入一个对象,而不是一个方法的一个对象。我现在正在清理代码。感谢您的评论

标签: java list loops infinite


【解决方案1】:

正如所指出的,您可以使用方法contains()。但是,最好只使用 Set 而不是列表,因为默认情况下集合需要唯一性。

* 代码示例 *

    public void testPoints() {
        Set<E> setClosestFirst = new LinkedHashSet<E>();
        for (int i = 1; i <= 100; ++i) {
            //create 100 random points/planes
            //add them to the set
            E anotherRandomE = new E(Calendar.getInstance().getTime().getTime() * i);
            setClosestFirst.add(anotherRandomE);
        }
        System.err.println("There were " + setClosestFirst.size() + " unique points created.");
    }

    public class Point {
        protected int x;
        protected int y;
    }

    /* Kind of a bad name for a class...perhaps MyCustomPoint would be better.
       Longer names in Java are usually best.
     */
    public class E extends Point {
        private int plane;

        public E(long seed) {
            Random random = new Random(seed);
            int minPlane = 0;
            int maxPlane = 1;
            int xYMin = 0;
            int xYMax = 10;
            this.plane = random.nextInt(maxPlane - minPlane) + minPlane; // random plane between 0 and 10
            this.x = random.nextInt(xYMax - xYMin) + xYMin;
            this.y = random.nextInt(xYMax - xYMin) + xYMin;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof E)) return false;

            E e = (E) o;

            if (this.x != e.x || this.y != e.y || this.plane != e.plane) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return plane * x * y * 13;
        }
    }

【讨论】:

  • 如果您仍想保留订单,请考虑使用 LinkedHashSet
  • 这是一个更大问题的一部分,所以我必须使用列表。
【解决方案2】:
boolean exist = false;
ListIterator<e> iterator = listClosestFirst.listIterator(0);

while (iterator.hasNext() && !exist) {
    exist = (e.getLocation()).equals((iterator.next()).getLocation());
}

if (!exist) {
    listClosestFirst.add(e);
}

由于您使用的是链表,因此迭代器效率更高。大约从 O(n!) 增强到 O(n)。

【讨论】:

  • 这很有意义。谢谢。
猜你喜欢
  • 2019-05-12
  • 2016-06-24
  • 2013-08-12
  • 2021-04-02
  • 2022-01-09
  • 2020-04-22
  • 1970-01-01
  • 2015-12-17
  • 2022-12-20
相关资源
最近更新 更多