使用TreeSet在Java中包含带有整数的()

时间:2010-10-06 17:58:32

标签: java contains treeset

import java.io.*;
import java.util.*;

class StepfordHouses {

    private ArrayList<Integer> houses; // A list containing houses
    private TreeSet<Integer> ordered; // An ordered treeset of houses
    private TreeSet<Integer> processed; // Elements already processed
    private String inpline[]; // An array of String holing houses heights in physical order
    private int disorientedindex; // The index for the Street
    private int size; // Number of houses in the Street

    public StepfordHouses() // Constructor for init
    {
        houses = new ArrayList<Integer>();
        ordered = new TreeSet<Integer>();
        processed = new TreeSet<Integer>();

        // Basic Input from Text-File (Codechef Requirment)
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    System.in));

            size = Integer.parseInt(br.readLine());
            inpline = br.readLine().split(" ");
        } catch (IOException e) {
            System.out.println("BAAAAAAAAAM!!");
        }

        for (int c = 0; c < size; c++) // Populating Houses
        {
            Integer tmp = Integer.parseInt(inpline[c]);
            houses.add(tmp);
            ordered.add(tmp);
        }
    }

    public int calcIndex() 
    {
        int c = 0;

        while (c < size) {
            Iterator<Integer> it = ordered.iterator();

            Integer h1 = houses.get(c); // Get an element from the raw ArrayList of Houses
            Integer h = it.next(); // Get an element from the Iterator

            while (h1.equals(h) != true) {
                if (processed.contains(h1) == false) { // The element is not already processed
                    System.out.println(h1 + " " + h);
                    disorientedindex++;
                }
                h = it.next(); // Get an element from the Iterator
            }

            processed.add(h1);
            c++;
            it = null;
        }

        return disorientedindex;
    }

}

public class Work {
    public static void main(String args[]) {
        StepfordHouses sh = new StepfordHouses();
        System.out.println(sh.calcIndex());
    }
}

contains()方法不像我期望的那样工作,即比较整数! 输出为15,当时为9  if(processed.contains(h1)==false)正常工作,当元素已经存在时返回true!

代码哪里错了?

1 个答案:

答案 0 :(得分:0)

逻辑是有缺陷的。 processed.add(h1);被称为N次,但processed.contains(h1)被称为N * N次。因此,根据输入,您可以使用迷失方向索引&lt;&gt; Ñ