วันอาทิตย์ที่ 7 ตุลาคม พ.ศ. 2550

Generics คืออะไร ?

การจัดเตรียมโครงสร้างของชนิดข้อมูลที่มากกว่าชนิดข้อมูลนั้น คล้ายๆ array แต่ไม่ได้ระบุ เพิ่มได้เรื่อยๆ
ความสามารถในการส่งข้อมูลของ Interface และ Method ได้
การสร้าง Generics Class:
LinkedList
E คือชนิดข้อมูลไม่ว่าจะเป็น premetive หรือ reference
เป็นชนิดข้อมูล ย่อยที่อยู่ใน Linkedlist
ตัวอย่างรูปแบบการสร้าง
public class LinkedList
extends AbstractSequentialList
implements List, Queue, Cloneable, java.io.Serializable{
private transient Entry header = new Entry(null, null, null);
private transient int size = 0;
public E getFirst() {
if (size==0) throw new NoSuchElementException();
return header.next.element;
}

ตัวอย่างการใช้งาน
LinkedList li = new LinkedList();
li.add(new Integer(0));
Integer i = li.iterator().next();

ตัวอย่าง
// Create a Vector of String type
Vector vs = new Vector();
vs.add(new Integer(5)); // Compile error!
vs.add(new String(“hello”));
String s = vs.get(0); // No casting needed
ตัวอย่าง
HashMap map = new HashMap();
map.put(“wombat”, new Mammal("wombat"));
Mammal w = map.get(“wombat”);
แค่นี้ก่อนนะครับไม่เข้าใจถามละกันครับอาจเข้าใจยากไปหน่อยนะครับแต่ถ้าไม่เข้าใจกลับ
ไปอ่านโครงสร้างข้อมูลเรื่อง Linklist

ไม่มีความคิดเห็น: