0

リストに値を挿入したいのですが、値がまだリストにない場合に限ります。リストに値を追加すると、リストのサイズも大きくなり、for ループの終了条件が満たされる方法がないため、これまでのコードは無限ループを作成します。これはより大きなプログラムの一部です。e は Point を拡張するオブジェクトの型です。次の点に注意してください。 e は Point を拡張します。e には値があります (Point から継承する座標に加えて)。リストが空の場合、リストに 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);
4

2 に答える 2

5

指摘したように、メソッドを使用できますcontains()。ただし、セットはデフォルトで一意性を必要とするため、リストの代わりにセットを使用する方がよい場合があります。

* コードサンプル *

    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;
        }
    }
于 2013-05-10T02:02:25.247 に答える
1
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) に強化されました。

于 2013-05-10T02:07:15.983 に答える