레이블이 자바 static인 게시물을 표시합니다. 모든 게시물 표시
레이블이 자바 static인 게시물을 표시합니다. 모든 게시물 표시

2013년 10월 29일 화요일

Java Colection,AbstractCollection 인터페이스 1. Collection 객체의 모임이며

Java Colection,AbstractCollection 인터페이스

1. Collection
 
객체의 모임이며, 직접 구현 안하며 Set이나 List중 하나를 구현한다.
크기 정보 추출
int size()
boolean isEmpty()
검색, 비교, 복사
boolean contains(Object o)
boolean containsAll(Collection c)
Iterator iterator()
Object[] toArray() : Collection 내의 객체의 배열을 반환
Object[] toArray(Object[] a)
객체 추가, 제거
boolean add(Object o)
boolean addAll(Collection c)
boolean remove(Object o)
boolean removeAll(Collection c) : c를 모두 제거
boolean retainAll(Collection c) : c를 제외한 객체 제거
clear()
특징
구성원 객체의 수가 변경되었으면 true를 반환
허용하지 않는 메쏘드는 UnsupportedOperationException 발생
add, addAll 메쏘드는 ClassCastException 발생 가능
null을 허용하지 않을 경우 NullPointerException 발생 가능
조건에 맞지 않을 경우 IllegalArgumentException 발생 가능
 
2. AbstractCollection
 
Collection 인터페이스 구현한 추상클래스
중복 허용
실제 저장 구조와 관계된 함수는 미구현
변경 불가능한 하위 Collection 구현 시 iterator(), size() 만 구현
변경 가능한 하위 Collection 구현 시
add() 구현하지 않으면  UnsupporedOperationException 발생
String toString()은 각 구성원 객체의 toString() 값을 출력한다.
 
 
[예제]

package onj;
 
//AbstractCollection을 상속한 사용자 정의 컬렉션
import java.util.*;
public class MyCollection extends AbstractCollection {
 private int size = 0;
 private Object[] arr = new Object[10];
 public int size() {
  return size;
 }
 public boolean add(Object o) {
  arr[size++] = o;
  return true;
 }
 public Iterator iterator() {
  return new Iterator() {
   private int current = -1;
   public boolean hasNext() {
    return current + 1 < size;
   }
   public Object next() {
    current++;
    if (size <= current)
     throw new NoSuchElementException();
    return arr[current];
   }
   public void remove() {
    if (current == -1 || size <= current) throw new NoSuchElementException();
    for (int i = current + 1; i < size; i++)
     arr[i - 1] = arr[i];
    current--;
    size--;
   }
  };
 }
 public static void main(String[] args) {
  MyCollection col = new MyCollection();
  col.add("OnJ1");
  col.add("OnJ2");
  System.out.println("size(): " + col.size());
  System.out.println("contains(): " + col.contains("second"));
  System.out.println("toString(): " + col);
  System.out.print("iterator: ");
  // 반복자
  Iterator iter = col.iterator();
  while (iter.hasNext()) {
   System.out.print(iter.next() + ", ");
  }
  System.out.println();
  System.out.print("toArray(): ");
  Object[] array = col.toArray();
  for (int i = 0; i < array.length; i++)
   System.out.print(array[i] + ", ");
  System.out.println();
  col.remove("first");
  System.out.println("remove(): " + col);
  MyCollection col2 = new MyCollection();
  col2.add("OnJ3");
  col2.add("OnJ4");
  System.out.println("containsAll(): " + col.containsAll(col2));
  col.addAll(col2);
  System.out.println("addAll(): " + col);
  col.removeAll(col2);
  System.out.println("removeAll(): " + col);
  col.clear();
  System.out.println("col.size() : " + col.size());
  System.out.println("clear(): " + col);
 }
}
 

[결과]
 
size(): 2
contains(): false
toString(): [OnJ1, OnJ2]
iterator: OnJ1, OnJ2,
toArray(): OnJ1, OnJ2,
remove(): [OnJ1, OnJ2]
containsAll(): false
addAll(): [OnJ1, OnJ2, OnJ3, OnJ4]
removeAll(): [OnJ1, OnJ2]
col.size() : 0
clear(): []

2013년 10월 21일 월요일

자바 싱글톤, 쓰레드 예제 (Java Thread Singleton)

자바 싱글톤, 쓰레드 예제 (Java Thread Singleton)

public class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton() {
        System.out.println("Sington Class의 인스턴스 생성!");                   
    }
    public static Singleton getInstance() {       
        return singleton;
    }                                        
}
 
public class Main extends Thread {
    public static void main(String[] args) {
        System.out.println("Start.");       
        Singleton obj1 = Singleton.getInstance();
  Singleton obj2 = Singleton.getInstance();
        if (obj1 == obj2){
   System.out.println("obj1 == obj2");
        }
  else {
   System.out.println("obj1 != obj2");
  }
    }
}
 
=======================================
 
 
public class Singleton {
    private static Singleton singleton = null;
    private Singleton() {
        System.out.println("인스턴스 생성...");
        slowdown();                            
    }
    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
    private void slowdown() {                  
        try {                                  
            Thread.sleep(10);                
        } catch (InterruptedException e) {     
        }                                      
    }                                          
}
 
 
public class Main extends Thread {
    public static void main(String[] args) {
        System.out.println("Start.");
        new Main("A").start();
        new Main("B").start();
        new Main("C").start();
        System.out.println("End.");
    }
    public void run() {
        Singleton obj = Singleton.getInstance();
        System.out.println(getName() + ": obj = " + obj);
    }
    public Main(String name) {
        super(name);
    }
}

2013년 8월 1일 목요일

java.util.TreeSet 클래스 – 예제

java.util.TreeSet 클래스 – 예제 
 
 
import java.awt.*;  import java.util.*;
public class TreeSetTest implements Comparator {
Set treeset;
public TreeSetTest() {
treeset = new TreeSet(this);
}
public void test() {
for(int i=0;i<5;i++) {
treeset.add(new Integer(i));
}
System.out.println("Sert Result : "+treeset);
}
public int compare(Object o1, Object o2) {
return ((Integer)o1).compareTo(o2);
}
public static void main(String[] args) {
TreeSetTest tst = new TreeSetTest();
tst.test();
}
}
 

(Static Member, Field)클래스멤버 - 클래스변수(필드)/클래스메소드

클래스필드(변수)
 클래스의 인스턴스가 아니라 그것이 정의된 클래스와  연관된다.
 static 한정자는 이 변수(필드)가 클래스필드임을 의미
 상수를 정의하는것이 클래스필드의 일반적인 사용이다.
  public static final double PI=3.14159;
  모든 클래스 필드가 상수인것은 아니다. Static만 기술하고 
  final은 빠질수도 있다.
 정적필드의 복사본은 오직 한 개 존재하며 전역변수
 같은 클래스 내부에서는 PI로 지칭되며 클래스 외부에서
  해당 변수(필드)를 유일하게 지칭하기 위해서는 클래스.PI 
   
 클래스메소드
 static 한정자로 선언된다. 
  public static double radiansToDegree(double rads)
- 객체가 아니라 클래스와 연관
  클래스의 외부에서 메소드를 호출하기 위해서는 클래스.메
  소드 형태로 가리킨다.
  double d = Circle.radiansToDegree(2.0);
  물론 그 클래스 내부에서는 클래스 이름을 지정할 필요가
  없다
 자신의 클래스의 모든 클래스변수(필드)와 클래스 메소드 
  를 사용할수 있다. 인스턴스 필드(변수)나 인스턴스 메소드
  는 사용할수 없다.