상세 컨텐츠

본문 제목

Generic Methods

Java

by techbard 2016. 7. 8. 21:45

본문

반응형



package GenericMethods;


import java.util.Random;


public class Driver {


    private static final int SIZE = 10;


    public static void main(String[] args) {

// we CANT'Y use primitive types in Generics!

Integer[] myInts;

myInts = new Integer[SIZE];

Random r = new Random();

for (int i = 0; i < myInts.length; i++) {

   myInts[i] = r.nextInt(SIZE);

}

for (Integer myInt : myInts) {

   System.out.println(myInt);

}


swapItems(0, 1, myInts);

System.out.println("==============================");

for (Integer myInt : myInts) {

   System.out.println(myInt);

}

    }


    public static <T> void swapItems(int i1, int i2, T[] items) {

T temp = items[i1];

items[i1] = items[i2];

items[i2] = temp;

    }


    public static <T> void printItems(T[] items) {

for (T item : items) {

   System.out.println("Next " + item.getClass().getName() + ": " + item);

}

    }

}


# 결과


9

2

3

1

7

4

6

9

2

8

==============================

2

9

3

1

7

4

6

9

2

8




# Animal.java


public class Animal {

    

    private String name;

    

    public Animal() {

    }


    public Animal(String name) {

this.name = name;

    }

    

    public String getName() {

        return name;

    }


    @Override

    public String toString() {

        return String.format("%s, %s\n", getClass(), this.name);

    }

}


# GernMethod.java


public class GernMethods {

    

    private static final int MAX = 5;

    

    public static void main(String[] args) {

intSwapTest();

System.out.println("====================");

animalSwapTest();

    }


    private static void animalSwapTest() {

Animal[] myAnimals = new Animal[MAX];

for (int i = 0; i < MAX; i++) {

   myAnimals[i] = new Animal(String.valueOf(i));

}

swapItem(0, 1, myAnimals);

for (Animal myAnimal : myAnimals) {

   System.out.println(myAnimal.getName());

}

    }


    private static void intSwapTest() {

Integer[] myInts;

myInts = new Integer[MAX];

for (int i = 0; i < MAX; i++) {

   myInts[i] = i;

}

swapItem(0, 1, myInts);


for (Integer myInt : myInts) {

   System.out.println(myInt);

}

    }


    private static <T> void swapItem(int i1, int i2, T[] items) {

T temp = items[i1];

items[i1] = items[i2];

items[i2] = temp;

    }


}



# 결과


1

0

2

3

4

====================

Item: 1 instance.

Item: 0 instance.

Item: 2 instance.

Item: 3 instance.

Item: 4 instance.



반응형

관련글 더보기

댓글 영역