Java List create custom List class to store only unique values

Description

Java List create custom List class to store only unique values

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class UniqueList<T> {
  private Set<T> masterSet = new HashSet<>();
  private List<T> innerList;


  public UniqueList() {
    innerList = new ArrayList<>();
  }/*from w w  w  . j a v  a  2s . c o m*/

  public UniqueList(int size) {
    innerList = new ArrayList<>(size);
  }

  public void add(T thing) {
    if (!masterSet.contains(thing)) {
      masterSet.add(thing);
      innerList.add(thing);
    }
  }
  public List<T> getList() {
    return innerList;
  }

  public T get(int index) {
    return innerList.get(index);
  }

  public Object[] toObjectArray() {
    int size = innerList.size();
    Object[] returnable = new Object[size];
    for (int i = 0; i < size; i++) {
      returnable[i] = innerList.get(i);
    }
    return returnable;
  }
}

public class Main {
  public static void main(String[] args) {
    UniqueList<String> ul = new UniqueList<>();
    ul.add("CSS");
    ul.add("CSS");
    ul.add("HTML");
    ul.add("HTML");
    ul.add("Java");
    ul.add("demo 2s.com");
    Object[] content = ul.toObjectArray();
    System.out.println(Arrays.toString(content));
  }
}



PreviousNext

Related