You are on page 1of 5

Basic classes trong java 1.

1 Cac lp Wrapper (Integer, Double, Float, ) va Array Byte, Integer, Float, Double, la nhng lp x ly v byte, s nguyn, s thc, no cha nhng phng tich tin ich giup x ly s nguyn, s thc nh compareTo, doubleValue, floatValue, longValue, notify, toString, Vi du: Integer i = new Integer(1); Double d1 = new Double(1.0002); Double d2 = i.doubleValue(); if(d1.compareTo(d2) == 0) { System.out.println(d1 + " equal " + d2); } else { System.out.println(d1 + " not equal " + d2); } Kt qua se in ra man hinh: 1.0 not equal 1.0002 Array (java.lang.reflect.Array) la lp cha cac phng thc static giup tao va quan ly mang d dang hn. Mt s phng thc trong lp Array nh: get ly mt i tng t mang getLength tra v kich thc mang getInt ly v mt s nguyn trong mang cac s nguyn getBoolean ly v gia tri boolean trong mang cac gia tri boolean set a mt i tng vao mang setInt a mt s nguyn vao mang Vi du: String[] a = { "Nguyen", "Kien" }; Array.set(a, 1, "Anh"); String iObject = Array.get(a, 1).toString(); System.out.println("Length:" + Array.getLength(a) + " objecAt1:" + iObject); //In ra Length:2 objecAt1:Anh boolean[] b = { true, false, true }; boolean bObject = Array.getBoolean(b, 2); System.out.println(bObject); //In ra true 1.2 Cac lp Collection (Collection, Set, List, Map, ArrayList, Vector, Hashtable, Hashset, HashMap) Cac lp v collection c t trong goi java.util. y la mi quan h gia cac lp collection

Java Collection Implementations Historical Hash table Resizable Array Balanced Tree LinkedList Interfaces Collection HashSet ArrayList TreeSet LinkedList Set HashSet TreeSet SortedSet TreeSet List ArrayList LinkedList Vector, Stack Map HashMap TreeMap HashTable, Properties SortedMap TreeMap Chung ta se i vao chi tit tng lp Collection la mt interface vi cac phng thc ph bin nht gom nhom cac i tng nh: add thm phn t vao mang isEmpty kim tra mang co rng khng remove xoa phn t khoi mang size ly kich thc mang clear xoa tt ca cac phn t trong mang toArray tra v mang cac i tng List la mt interface dung cha danh sach lin tuc, no k tha t Collection interface nn no co cac ham trong Collection va mt s ham ring cua no nh: get ly phn t ra khoi mang

indexOf tim phn t trong mang set thay th phn t trong mang ArrayList la mt lp k tha t AbstractList va implement List interface va mt vai interface khac. Vi du: ArrayList<String> a = new ArrayList(); a.add("Kien"); a.add(0, "Anh"); for(String s : a) { System.out.print(s + "\t"); //In ra Anh Kien } Set, SortedSet, HashSet, TreeSet cung la nhng lp x ly lin quan n collection tuy nhin chung khac bn nhom List la cac phn t trong Set la duy nht. Vi du: Set set = new HashSet(); set.add("Bernadine"); set.add("Elizabeth"); set.add("Gene"); set.add("Elizabeth"); set.add("Clara"); System.out.println(set); Chung ta se nhn c chui in ra la: [Bernadine, Gene, Elizabeth, Clara] Set, SortedSet la interface con HashSet va TreeSet la nhng lp implement interface Set va k tha t AbstractSet. TreeSet la collection c sp xp tc la cac phn t khi a vao TreeSet se t ng c a ung vi tri theo th t sp xp, con HashSet thi khng. Vi du: Set set = new TreeSet(); set.add("Bernadine"); set.add("Elizabeth"); set.add("Gene"); set.add("Elizabeth"); set.add("Clara"); System.out.println(set); Ta se nhn c kt qua: [Bernadine, Clara, Elizabeth, Gene] Map, SortedMap, HashMap, TreeMap la nhng lp dung x ly collection theo dang key-value. Map, SortedMap la interface va no khng k tha t Collection interface nh nhng interface trn. Con HashMap va TreeMap la hai lp implement Map interface va k tha t AbstractMap Vi du: Map<Integer, String> map = new HashMap(); map.put(3, "Kien"); map.put(1, "Nguyen"); map.put(2, "Anh"); System.out.println(map); Map sortedMap = new TreeMap(map); System.out.println(sortedMap); Kt qua in ra man hinh se la: {1=Nguyen, 2=Anh, 3=Kien} {1=Nguyen, 2=Anh, 3=Kien} Chung ta co mt vai lp ra i trc nh nh Vector, HashTable Vector la mt lp tng t ArrayList v mt x ly tuy nhin chung co s khac bit la Vector thi la ng b (Synchronized) va c dung nhiu trong ng dung a lung (multithreading). Chinh vi ng b nn s dung vector se cho tc chm hn mt chut so vi dung ArrayList.

HashTable la lp tng t HashMap v mt y nghia, va HashTable cung la ng b va c dung nhiu trong ng dung a lung. Con HashMap thi khng ng b, tuy nhin chung ta co th thm chc nng ng b cho HashMap nhng mc inh thi HashMap khng co. HashMap ra i sau nn no co ve hin ai va c s dung nhiu hn Hashtable Vi du: Hashtable<Integer, String> map = new Hashtable<Integer, String>(); map.put(3, "Kien"); map.put(1, "Nguyen"); map.put(2, "Anh"); System.out.println(map); Kt qua in ra se la: {3=Kien, 2=Anh, 1=Nguyen} 1.3 Nhom lp v String (String, StringBuffer, StringBuilder) String la mt i tng trong java dung x ly chui ky t. Gia tri cua i tng mt khi khi tao thi khng th thay i. Vi du: String str = "Luvina"; str += "Company"; System.out.println(str); Trong vi du trn chui LuvinaCompany c in ra man hinh, tuy nhin i tng str khng thay i ma la co mt i tng khac c tao ra co gia tri la chui LuvinaCompany ri sau o gan vao i tng str. Mt s phng thc thng dung trong lp String nh: length ly chiu dai hin tai cua chui substring ly ra mt chui trong chui hin hanh compareTo so sanh 2 chui co xet ky t hoa, thng compareToIgnoreCase so sanh 2 chui bo qua ky t hoa thng
// So sah 2 chu khng phn bi hoa, thg n i t n System.out.println("Le Thanh Vu".compareToIgnoreCase("le So sah 2 chu n i System.out.println("Le thanh vu")); // 0

compareTo(s): so snh phn bit hoa thng vi chui s.


// Thanh Vu".compareTo("Le Thanh Vu")); // 0

vi du: String str = "Luvina"; System.out.println("Length: " + str.length() + " substring(1,2): " + str.substring(1, 2)); Ta nhn c kt qua trn man hinh nh sau: Length: 6 substring(1,2): u StringBuffer va StringBuilder cung la i tng trong java x ly chui nhng chung khac String ch la gia tri tao ra cua chung co th thay i c ma khng cn phai tao mt i tng mi trong b nh. Thc ra khi chung ta x ly vic thay i gia tri trn String thi bn di trinh JVM se dung cac i tng StringBuffer va StringBuilder x ly va tao ra cac i tng String mi. Vi du: StringBuffer str = new StringBuffer("Luvina"); str.append("Company"); System.out.println(str); //In ra LuvinaCompany T c im trn ta co th thy khi x ly chui ma gia tri se hay thay i (cng chui, ct chui, ) thi nn dung StringBuffer hoc StringBuilder se cho tc nhanh hn so vi s dung String. Mt s phng thc thng dung trong StringBuffer va StringBuilder: append thm mt chui vao cui chui ang co insert chen mt chui vao chui ang co replace thay th mt chui delete xoa mt chui trong chui hin hanh lastIndexOf tim mt chui reverse ao ngc mt chui Vi du: StringBuffer str = new StringBuffer("Luvina"); System.out.println("Length: " + str.length() + " substring(1,2): " + str.substring(1, 2) + " str.append(\" Company\"): " + str.append(" Company") + " str.lastIndexOf(\"n\"): " + str.lastIndexOf("n") + " str.reverse: " + str.reverse());

Ta thu c kt qua trn man hinh t oan code trn nh sau: Length: 6 substring(1,2): u str.append(" Company"): Luvina Company str.lastIndexOf("n"): 12 str.reverse: ynapmoC anivuL 1.4 Cac lp tin ich khac (StringTokenizer, Date, Calendar, SimpleDateFormat, Arrays) StringTokenizer (java.util.StringTokenizer) la mt lp tin ich giup tach cac chui (string) c ngn cach bi cac ky t Vi du: String s = "subject emo StringTokenizer"; StringTokenizer st = new StringTokenizer(s, ":"); while(st.hasMoreTokens()) { String key = st.nextToken(); String val = st.nextToken(); System.out.println(key + ":" + val);//In subject emo StringTokenizer } Date (java.util.Date) la mt lp tin ich x ly v ngay thang Vi du: Date dObject = new Date(2009, 12, 22); System.out.println(dObject.toString()); //In Sat Jan 22 00:00:00 ICT 3910 System.out.println(dObject.getDate()); //In 22 Calendar la mt lp tru tng giup h tr trong vic bin i thng tin ngay thang. Vi du: Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 0); Date dObject = cal.getTime(); System.out.println(dObject.toString()); //In Tue Dec 22 17:28:46 ICT 2009 SimpleDateFormat (java.text. SimpleDateFormat) la mt lp tin ich giup cho vic inh dang va trich thng tin thi gian. Vi du: Date date = new Date(); SimpleDateFormat sdf; sdf = new SimpleDateFormat("hh:mm:ss"); System.out.println(sdf.format(date)); //In 05:35:38 sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz"); System.out.println(sdf.format(date)); //In 22 Dec 2009 05:35:38 ICT Arrays (java.util.Arrays) la lp cha cac phng thc static giup cho vic thay i mang (sp xp, tim kim, thay th) d dang hn. No la b sung cho lp Array. Mt s phng thc trong lp Arrays nh: binarySearch tim kim phn t trong mang dung thut toan tim kim nhi phn copyOf sao chep mt mang vi chiu dai copyOfRange sao chep mt mang vi mt vung t vi tri u n vi tri cui equals so sanh 2 mang sort sp xp mang Vi du: String[] a = { "Nguyen", "Anh", "Kien" }; String[] b = Arrays.copyOf(a, 2); int indexOfAnh = Arrays.binarySearch(a, "Anh"); /*sort a array*/

Arrays.sort(a); System.out.println(indexOfAnh); //In ra 1 because find Anh before sorting a array System.out.println(Arrays.toString(a)); //In ra [Anh, Kien, Nguyen] System.out.println(Arrays.toString(b)); //In ra [Nguyen, Anh] 1.5 RegularExpression Regular Expression hay con goi la biu thc chinh quy dung chi cach thc chung ta nhn bit, kim tra mt chui (biu thc) co ung nh inh dang chung ta mong mun hay khng. Trong java hin nay co 2 lp la Pattern va Matcher (java.util.regex) giup ta x ly cac vn n lin quan n regular expression. Pattern la lp dung bin dich biu thc, kt qua bin dich tao ra i tng thuc lp Matcher kim tra chui ky t co ung biu thc o. Mt vai phng thc cua lp Pattern nh: compile bin dich biu thc trong pattern matcher tao ra i tng thuc lp Matcher t pattern matches kim tra chui co ung vi biu thc trong pattern Matcher la lp c tao ra t Pattern va dung thc hin nhng vic nh match, tim kim. Mt vai phng thc trong lp Matcher nh: find tim kim chui ma match vi mu biu thc matches kim tra chui co match vi mu biu thc Mt vai pattern n gian: ^ phu inh $ kt thuc mt pattern [abc] ky t a, b va c [^abc] bt ky ky t nao tr a, b, c [a-z0-9] cac ky t a n z va 0 n 9 Vi du kim tra mt chui vi cac ky t bt buc: Pattern pat = Pattern.compile("Nguyen.*Kien"); Matcher matcher = pat.matcher("Nguyen Anh Kien"); boolean flag = matcher.matches(); System.out.println(flag); //In ra true Vi du ban cn kim tra in thoai ung inh dang XXX-XXXX-XXXX, mi khi X co it nht 1 ky t va ti a 3 4-4 ky t: String phone = "59-1111-1112"; String phoneNumberPattern = "^[0-9]{1,3}-[0-9]{1,4}-[0-9]{1,4}$"; boolean isMatch = Pattern.matches(phoneNumberPattern, phone); System.out.println(isMatch); //In ra true Vi du v kim tra ia chi email /*Check email format*/ String email = "nakien2a@yahoo.com"; String emailPattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-z]{2,7}$"; boolean isMatch = Pattern.matches(emailPattern, email); System.out.println(isMatch); //In ra true 0000000000 Theo bloger nguyenanhkien