خرید بک لینک

Vote count: 0

How do you count the number of distinct Strings in an ArrayList without using the Set data structure in the Java libraries?

I made two ArrayLists, one stored and one empty and want to store the empty one with distinct Strings. What am I doing wrongly?

public void distinctCount (WordStream words) {
ArrayList<String> loaded = new ArrayList<String>();
  ArrayList<String> empty = new ArrayList<String>();
  int count = 0;

  // Fill loaded with word stream
  for(String i : words) {
    loaded.add(i);
  }

  // Fill empty with loaded
  // Catch collisions
  for(int i = 0; i < loaded.size(); i++) {
    if(loaded.get(i) != empty.get(i)) {
      empty.add(loaded.get(i));
    }
  }
  retu empty.size();
}

asked 4 mins ago

1 Answer

Vote count: 0

The problem is that you're comparing only corresponding elements. Meaning that you compare the nth element with the nth element in the second arraylist.

The straightforward solution would be having nested loops: for each element in the first arraylist, loop over all elements in the second array list, if no match found - you know it's distinct. This solution's complexity is O(n2).

answered 48 secs ago

برچسب: نویسنده: استخدام کار تاريخ: دوشنبه 24 اسفند 1394 ساعت: 15:13

صفحه بندی