remove duplicate from array

       Write a program a remove duplicates from array and return a new array. with out using any collection API.


  1. import java.util.Arrays;

  2. class MyArray<E> {
  3. static int length = 0;
  4. static int capacity = 10;
  5. static Object arr[];
  6. MyArray(){
  7.  arr = new Object[capacity];
  8. }
  9. public void add(E value) {
  10. if (capacity == length) {
  11. increaseCapacity();
  12. }
  13. arr[length] = value;
  14. length++;
  15. }

  16. public static void increaseCapacity() {
  17. capacity=capacity*2;
  18. arr=Arrays.copyOf(arr, capacity);
  19. }

  20. public static int size() {
  21. return length;
  22. }
  23. public E get(int index) {
  24. if(index>length){
  25. throw new ArrayIndexOutOfBoundsException();
  26. }
  27. else return (E) arr[index];
  28. }
  29. public boolean contain(E value) {
  30. for(int i=0;i<length;i++){
  31. if(arr[i]==value)
  32. return true;
  33. }
  34. return false;
  35. }
  36. }

  37. public class Array1 {
  38. public static <E> MyArray add(E arr[]) {
  39. MyArray m=new MyArray();
  40. for(int i=0;i<arr.length;i++){
  41. if(!m.contain(arr[i])){
  42. m.add(arr[i]);
  43. }
  44. }
  45. return m;
  46. }

  47. public static void main(String[] args) {
  48.               // create any data type array 
  49. String[] arr = {"1","1","2","0"};
  50. MyArray m= add(arr);
  51. System.out.println("length: "+m.length);
  52. for (int i = 0; i < m.length; i++) {
  53. System.out.println(m.get(i));
  54. }
  55. }
  56. }


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation