remove duplicate from array
Write a program a remove duplicates from array and return a new array. with out using any collection API.
- import java.util.Arrays;
- class MyArray<E> {
- static int length = 0;
- static int capacity = 10;
- static Object arr[];
- MyArray(){
- arr = new Object[capacity];
- }
- public void add(E value) {
- if (capacity == length) {
- increaseCapacity();
- }
- arr[length] = value;
- length++;
- }
- public static void increaseCapacity() {
- capacity=capacity*2;
- arr=Arrays.copyOf(arr, capacity);
- }
- public static int size() {
- return length;
- }
- public E get(int index) {
- if(index>length){
- throw new ArrayIndexOutOfBoundsException();
- }
- else return (E) arr[index];
- }
- public boolean contain(E value) {
- for(int i=0;i<length;i++){
- if(arr[i]==value)
- return true;
- }
- return false;
- }
- }
- public class Array1 {
- public static <E> MyArray add(E arr[]) {
- MyArray m=new MyArray();
- for(int i=0;i<arr.length;i++){
- if(!m.contain(arr[i])){
- m.add(arr[i]);
- }
- }
- return m;
- }
- public static void main(String[] args) {
- // create any data type array
- String[] arr = {"1","1","2","0"};
- MyArray m= add(arr);
- System.out.println("length: "+m.length);
- for (int i = 0; i < m.length; i++) {
- System.out.println(m.get(i));
- }
- }
- }
Comments
Post a Comment