Sunteți pe pagina 1din 26

Java Programs

Comparator and Comparable Example

Page 1 of 26

In real life, objects are often comparable. For example, Dad's car is more expensive than Mom's, this dictionary is thicker than those books, Granny is older than Auntie Mollie (well, yeah, living objects, too, are comparable), and so forth. In writing object-oriented programs, there are often needs to compare instances of the same class. And once instances are comparable, they can be sorted. As an example, given two Employees, you may want to know which one has stayed in the organization longer. Or, in a search method for Person instances with a first name of Larry, you may want to display search results sorted by age. This article teaches you how to design your class to make its instances comparable by using the java.lang.Comparable and java.util.Comparator interfaces and presents three examples that illustrate both interfaces. Most Java programmers know how to sort the elements of a String array by using the sort method of java.util.Arrays. For String instances in an ArrayList, you can sort them with the sort method of the java.util.Collections class. The code in Listing 1 shows how to use Arrays.sort to order String instances. Listing 1: Sorting String Instances Using Arrays.sort import java.util.Arrays; String animals[] = new String[4]; animals[0] = "snake"; animals[1] = "kangaroo"; animals[2] = "wombat"; animals[3] = "bird"; for (int i=0; i<4; i++) { System.out.println("animal " + i + " : " + animals[i]); } Arrays.sort(animals); for (int i=0; i<4; i++) { System.out.println("animal " + i + " : " + animals[i]); } If you run the program, the first for loop gives you the name of animals as follows: animal 0 : snake animal 1 : kangaroo animal 2 : wombat animal 3 : bird And, the second for loop prints the animals sorted alphabetically. animal 0 : bird animal 1 : kangaroo animal 2 : snake animal 3 : wombat With the java.util.Collections class's sort method, you can sort String instances in an ArrayList, as shown in Listing 2. Listing 2: Sorting String Instances Using Collections.sort import java.util.ArrayList; import java.util.Collections; ArrayList insects = new ArrayList(); insects.add("mosquito"); insects.add("butterfly"); insects.add("dragonfly"); insects.add("fly"); int size = insects.size();

for (int i=0; i<size; i++) { System.out.println("insect " + i + " : " + (String) insects.get(i)); } Collections.sort(insects); for (int i=0; i<size; i++) { System.out.println("insect " + i + " : " + (String) insects.get(i)); } The first for loop in Listing 2 produces the following output: insect 0 : mosquito insect 1 : butterfly insect 2 : dragonfly insect 3 : fly The second for loop prints the following: insect 0 : butterfly insect 1 : dragonfly insect 2 : fly insect 3 : mosquito However, suppose we have a Person class, as in Listing 3. Listing 3: The Person Class class Person { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

Java Programs

Page 2 of 26

In another part of the program, we construct four instances of the Person class and populate them with names and ages: Person[] persons = new Person[4]; persons[0] = new Person(); persons[0].setFirstName("Elvis"); persons[0].setLastName("Goodyear"); persons[0].setAge(56);

Java Programs
persons[1] = new Person(); persons[1].setFirstName("Stanley"); persons[1].setLastName("Clark"); persons[1].setAge(8); persons[2] = new Person(); persons[2].setFirstName("Jane"); persons[2].setLastName("Graff"); persons[2].setAge(16); persons[3] = new Person(); persons[3].setFirstName("Nancy"); persons[3].setLastName("Goodyear"); persons[3].setAge(69);

Page 3 of 26

How do we sort these Person instances by age or by name? Using the java.util.Arrays class' sort method, as in: Arrays.sort(persons); will throw a ClassCastException. You can, of course, write your own code to sort them using an algorithm such as quick sort, bubble sort, or others, but that's impractical. The easy solution is to implement the java.lang.Comparable interface. Using the java.lang.Comparable Interface Implement the Comparable interface to make class instances comparable. This interface has one method, compareTo, which determines how to compare two instances of the class. The signature of this method is: public int compareTo(Object o) The compareTo method accepts Object, so you can pass it an instance of any type. However, chances are that you want to make sure to compare two instances of the same type. It does not make sense to compare an elephant with an ant, for example. Therefore, you can throw a java.lang.ClassCastException if the argument of this method is not the same type as your class. The compareTo method returns zero if the object passed is equal to this instance. It returns a positive integer or a negative integer if this object is greater or smaller than the passed object, respectively. Let's have a look at the examples in Listing 4 and Listing 5. Listing 4 presents a Person class that implements the Comparable interface. Notice that a Person object is older if its age value is greater than the object compared. Listing 5 shows the Testing class that constructs four instances of the Person class and sorts them by age. Both classes in Listings 4 and 5 reside in the comparable.ex01 package. Listing 4: The Person Class That Implements the Comparable Interface package comparable.ex01; class Person implements Comparable { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName;

Java Programs

Page 4 of 26

public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int compareTo(Object anotherPerson) throws ClassCastException { if (!(anotherPerson instanceof Person)) throw new ClassCastException("A Person object expected."); int anotherPersonAge = ((Person) anotherPerson).getAge(); return this.age - anotherPersonAge; } } Listing 5: The comparable.ex01.Testing Class package comparable.ex01; import java.util.Arrays; import java.util.ArrayList; public class Testing { public static void main(String[] args) { Person[] persons = new Person[4]; persons[0] = new Person(); persons[0].setFirstName("Elvis"); persons[0].setLastName("Goodyear"); persons[0].setAge(56); persons[1] = new Person(); persons[1].setFirstName("Stanley"); persons[1].setLastName("Clark"); persons[1].setAge(8); persons[2] = new Person(); persons[2].setFirstName("Jane"); persons[2].setLastName("Graff"); persons[2].setAge(16); persons[3] = new Person(); persons[3].setFirstName("Nancy"); persons[3].setLastName("Goodyear"); persons[3].setAge(69); System.out.println("Natural Order"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons); System.out.println(); System.out.println("Sorted by age");

Java Programs
for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } } } The result of the code in Listing 5 is as follows: Natural Order Goodyear, Elvis. Age:56 Clark, Stanley. Age:8 Graff, Jane. Age:16 Goodyear, Nancy. Age:69 Sorted by age Clark, Stanley. Age:8 Graff, Jane. Age:16 Goodyear, Elvis. Age:56 Goodyear, Nancy. Age:69 Using the java.util.Comparator Class

Page 5 of 26

Implementing the Comparable interface enables you to define one way to compare instances of your class. However, objects are sometimes comparable in many ways. For example, two Person objects may need to be compared by age or by last/first name. In cases like this, create a Comparator that defines how to compare two objects. To make objects comparable in two ways, then you need two comparators. To create a comparator, write a class that implements the java.util.Comparator interface--the compare method. This method has the following signature: public int compare(Object o1, Object o2) The compare method returns zero if o1 and o2 are equal, a negative integer if o1 is less than o2, and a positive integer if o1 is greater than o2. Just as in the compareTo method of Comparable, you define what makes an object equal or less/greater than another object. As an example, let's write two comparators for the Person class. This example consists of four classes, all of which reside in the comparable.ex02 package. The Person class is similar to the one in the previous example, and is reprinted in Listing 6 for reading convenience. Listings 7 and 8 present two comparators of Person objects (by last name and by first name), and Listing 9 offers the class that instantiates the Person class and the two comparators. Listing 6: The comparable.ex02.Person Class package comparable.ex02; class Person implements Comparable { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }

public String getLastName() { return lastName; }

Java Programs

Page 6 of 26

public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int compareTo(Object anotherPerson) throws ClassCastException { if (!(anotherPerson instanceof Person)) throw new ClassCastException("A Person object expected."); int anotherPersonAge = ((Person) anotherPerson).getAge(); return this.age - anotherPersonAge; } } Listing 7: The comparable.ex02.LastNameComparator Class package comparable.ex02; import java.util.Comparator; public class LastNameComparator implements Comparator { public int compare(Object person, Object anotherPerson) { String lastName1 = ((Person) person).getLastName().toUpperCase(); String firstName1 = ((Person) person).getFirstName().toUpperCase(); String lastName2 = ((Person) anotherPerson).getLastName().toUpperCase(); String firstName2 = ((Person) anotherPerson).getFirstName().toUpperCase(); if (!(lastName1.equals(lastName2))) return lastName1.compareTo(lastName2); else return firstName1.compareTo(firstName2); } } Listing 8: The comparable.ex02.FirstNameComparator Class package comparable.ex02; import java.util.Comparator; public class FirstNameComparator implements Comparator { public int compare(Object person, Object anotherPerson) { String lastName1 = ((Person) person).getLastName().toUpperCase(); String firstName1 = ((Person) person).getFirstName().toUpperCase(); String lastName2 = ((Person) anotherPerson).getLastName().toUpperCase(); String firstName2 = ((Person) anotherPerson).getFirstName().toUpperCase(); if (!(firstName1.equals(firstName2))) return firstName1.compareTo(firstName2); else return lastName1.compareTo(lastName2); } } Listing 9: The comparable.ex02.Testing Class package comparable.ex02; import java.util.Arrays; import java.util.ArrayList;

Java Programs
public class Testing { public static void main(String[] args) { Person[] persons = new Person[4]; persons[0] = new Person(); persons[0].setFirstName("Elvis"); persons[0].setLastName("Goodyear"); persons[0].setAge(56); persons[1] = new Person(); persons[1].setFirstName("Stanley"); persons[1].setLastName("Clark"); persons[1].setAge(8); persons[2] = new Person(); persons[2].setFirstName("Jane"); persons[2].setLastName("Graff"); persons[2].setAge(16); persons[3] = new Person(); persons[3].setFirstName("Nancy"); persons[3].setLastName("Goodyear"); persons[3].setAge(69); System.out.println("Natural Order"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons, new LastNameComparator()); System.out.println(); System.out.println("Sorted by last name"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons, new FirstNameComparator()); System.out.println(); System.out.println("Sorted by first name"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons); System.out.println(); System.out.println("Sorted by age"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge();

Page 7 of 26

System.out.println(lastName + ", " + firstName + ". Age:" + age); } } } If you run the comparable.ex02.Testing class, you can see the following result: Natural Order Goodyear, Elvis. Age:56 Clark, Stanley. Age:8 Graff, Jane. Age:16 Goodyear, Nancy. Age:69 Sorted by last name Clark, Stanley. Age:8 Goodyear, Elvis. Age:56 Goodyear, Nancy. Age:69 Graff, Jane. Age:16 Sorted by first name Goodyear, Elvis. Age:56 Graff, Jane. Age:16 Goodyear, Nancy. Age:69 Clark, Stanley. Age:8 Sorted by age Clark, Stanley. Age:8 Graff, Jane. Age:16 Goodyear, Elvis. Age:56 Goodyear, Nancy. Age:69 Integrating Comparators in Comparable Classes

Java Programs

Page 8 of 26

The previous example with the Comparator interface works fine. However, the drawback is that it requires multiple classes. This means more maintenance work for the users of your comparable class. The next example shows how to integrate the comparators inside of the comparable class by making the comparators anonymous classes. This example has two classes: comparable.ex03.Person (Listing 10) and comparable.ex03.Testing (Listing 11). Note the two anonymous inner classes at the end of the Person class, and notice also in the Testing class how comparison is conducted. Listing 10: The comparable.ex03.Person Class package comparable.ex03; import java.util.Comparator; public class Person implements Comparable { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName;

} public int getAge() { return age; } public void setAge(int age) { this.age = age; }

Java Programs

Page 9 of 26

public int compareTo(Object anotherPerson) throws ClassCastException { if (!(anotherPerson instanceof Person)) throw new ClassCastException("A Person object expected."); int anotherPersonAge = ((Person) anotherPerson).getAge(); return this.age - anotherPersonAge; } public static Comparator LastNameComparator = new Comparator() { public int compare(Object person, Object anotherPerson) { String lastName1 = ((Person) person).getLastName().toUpperCase(); String firstName1 = ((Person) person).getFirstName().toUpperCase(); String lastName2 = ((Person) anotherPerson).getLastName().toUpperCase(); String firstName2 = ((Person) anotherPerson).getFirstName().toUpperCase(); if (!(lastName1.equals(lastName2))) return lastName1.compareTo(lastName2); else return firstName1.compareTo(firstName2); } }; public static Comparator FirstNameComparator = new Comparator() { public int compare(Object person, Object anotherPerson) { String lastName1 = ((Person) person).getLastName().toUpperCase(); String firstName1 = ((Person) person).getFirstName().toUpperCase(); String lastName2 = ((Person) anotherPerson).getLastName().toUpperCase(); String firstName2 = ((Person) anotherPerson).getFirstName().toUpperCase(); if (!(firstName1.equals(firstName2))) return firstName1.compareTo(firstName2); else return lastName1.compareTo(lastName2); } }; } Listing 11: The comparable.ex03.Testing Class package comparable.ex03; import java.util.Arrays; import java.util.ArrayList; public class Testing { public static void main(String[] args) { Person[] persons = new Person[4]; persons[0] = new Person(); persons[0].setFirstName("Elvis"); persons[0].setLastName("Goodyear"); persons[0].setAge(56); persons[1] = new Person(); persons[1].setFirstName("Stanley"); persons[1].setLastName("Clark"); persons[1].setAge(8);

persons[2] = new Person(); persons[2].setFirstName("Jane"); persons[2].setLastName("Graff"); persons[2].setAge(16);

Java Programs

Page 10 of 26

persons[3] = new Person(); persons[3].setFirstName("Nancy"); persons[3].setLastName("Goodyear"); persons[3].setAge(69); System.out.println("Natural Order"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons, Person.LastNameComparator); System.out.println(); System.out.println("Sorted by last name"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons, Person.FirstNameComparator); System.out.println(); System.out.println("Sorted by first name"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons); System.out.println(); System.out.println("Sorted by age"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } } } The result of the Testing class is the same as the previous example. However, note that the comparators are inside of the Person class. To sort instances of the Person class by last name, you just need to use: Arrays.sort(persons, Person.LastNameComparator); To sort them by first name: Arrays.sort(persons, Person.LastNameComparator);

ONJava.com.

Java Programs

Page 11 of 26

1. Reverese a number package project.test; import java.util.Scanner; // program uses class Scanner public class ReverseDigits { static Scanner console = new Scanner(System.in); public static void main( String args[]) { String number; System.out.println("Enter an integer"); number = console.nextLine(); reverse (number); // print the method reverse } // end method main public static void reverse ( String num ) { int lastDigit; // the last digit returned when reversed int reverse = 0; for(int i = num.length()-1; i >= 0; i--) { System.out.print(num.charAt(i)); } System.out.println(" is integer with its digits reversed."); int res=Integer.parseInt(num); System.out.println("Result ="+res); } } Shortest: new StringBuilder(input + "").reverse().toString() 2. Deadlock package project.test; /** * This is a demonstration of how NOT to write multi-threaded programs. * It is a program that purposely causes deadlock between two threads that * are both trying to acquire locks for the same two resources. * To avoid this sort of deadlock when locking multiple resources, all threads * should always acquire their locks in the same order. **/ public class Deadlock { public static void main(String[ ] args) { // These are the two resource objects we'll try to get locks for final Object resource1 = "resource1"; final Object resource2 = "resource2"; // Here's the first thread. It tries to lock resource1 then resource2 Thread t1 = new Thread( ) { public void run( ) {

// Lock resource 1 synchronized(resource1) { System.out.println("Thread 1: locked resource 1"); // Pause for a bit, simulating some file I/O or // something. Basically, we just want to give the // other thread a chance to run. Threads and deadlock // are asynchronous things, but we're trying to force // deadlock to happen here... try { Thread.sleep(50); } catch (InterruptedException e) { } // Now wait 'till we can get a lock on resource 2 synchronized(resource2) { System.out.println("Thread 1: locked resource 2"); } } } }; // Here's the second thread. It tries to lock resource2 then resource1 Thread t2 = new Thread( ) { public void run( ) { // This thread locks resource 2 right away synchronized(resource2) { System.out.println("Thread 2: locked resource 2"); // Then it pauses, just like the first thread. try { Thread.sleep(50); } catch (InterruptedException e) { } // Then it tries to lock resource1. But wait! Thread // 1 locked resource1, and won't release it 'till it // gets a lock on resource2. This thread holds the // lock on resource2, and won't release it 'till it // gets resource1. We're at an impasse. Neither // thread can run, and the program freezes up. synchronized(resource1) { System.out.println("Thread 2: locked resource 1"); } } } }; // Start the two threads. If all goes as planned, deadlock will occur, // and the program will never exit. t1.start( ); t2.start( ); } } Convert a given string as "11/12/2010" to a Date object. /*Convert a given string as "11/12/2010" to a Date object. */ package project.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDate { public static void main(String args[]) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy"); String dateString="11/12/2010"; Date d=sdf.parse(dateString); System.out.println(d); } } Output:

Java Programs

Page 12 of 26

Sat Dec 11 00:00:00 IST 2010 FILE I/O STREAM Byte Streams Note:

Java Programs

Page 13 of 26

1. 2.

All byte stream classes are descended from InputStream and OutputStream.

There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream.

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Character Streams Note: All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) {

outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } }

Java Programs

Page 14 of 26

NOTE: The most important difference is that CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream. Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from. However, in CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits. Line-Oriented I/O import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; public class CopyLines { public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; try { inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } Note: Invoking readLine returns a line of text with the line. Buffered Streams Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

A program can convert an unbuffered stream into a buffered stream using the wrapping idiom we've used several times now, where the unbuffered stream object is passed to the constructor for a buffered stream class. Here's how you might modify the constructor invocations in the CopyCharacters example to use buffered I/O: inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt")); There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams. How do I sort a list with multiple sort parameters? public class Person { private int id; private String name, address; public static Comparator<Person> getComparator(SortParameter... sortParameters) { return new PersonComparator(sortParameters); } public enum SortParameter { ID_ASCENDING, ID_DESCENDING, NAME_ASCENDING, NAME_DESCENDING, ADDRESS_ASCENDING, ADDRESS_DESCENDING } private static class PersonComparator implements Comparator<Person> { private SortParameter[] parameters; private PersonComparator(SortParameter[] parameters) { this.parameters = parameters; } public int compare(Person o1, Person o2) { int comparison; for (SortParameter parameter : parameters) { switch (parameter) { case ID_ASCENDING: comparison = o1.id - o2.id; if (comparison != 0) return comparison; break; case ID_DESCENDING: comparison = o2.id - o1.id; if (comparison != 0) return comparison; break; case NAME_ASCENDING: comparison = o1.name.compareTo(o2.name); if (comparison != 0) return comparison; break; case NAME_DESCENDING: comparison = o2.name.compareTo(o1.name); if (comparison != 0) return comparison; break; case ADDRESS_ASCENDING: comparison = o1.address.compareTo(o2.address); if (comparison != 0) return comparison; break; case ADDRESS_DESCENDING: comparison = o2.address.compareTo(o1.address); if (comparison != 0) return comparison; break; } } return 0; } }

Java Programs

Page 15 of 26

} //

Java Programs

Page 16 of 26

package de.vogella.algorithms.sort.standardjava; import java.util.Comparator; public class MyIntComparable implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return (o1>o2 ? -1 : (o1==o2 ? 0 : 1)); } } package de.vogella.algorithms.sort.standardjava; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Simple2 { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(4); list.add(3); list.add(7); list.add(2); list.add(1); Collections.sort(list, new MyIntComparable()); for (Integer integer : list) { System.out.println(integer); } } } Array--Java Multi-Dimensional Arrays Multi dimensional arrays are arrays of arrays. To declare a multi dimensional array variable, specify each additional index using another set of square brackets. An example is given below for two dimensional array: int sample[][] = new int[3][3]; We can specify memory for first dimension first, and we can assign memory for second dimension later as given below: int sample[][] = new int[3][]; int sample[0] = new int[2]; int sample[1] = new int[2]; int sample[2] = new int[2]; The advantage of assigning memory for second dimension is your second dimension can be of any lengths, cannot be fixed length. Program: How to convert Array to List in java? package com.java2novice.arrays; import java.util.Arrays; import java.util.List; public class ArraysToList {

Java Programs
public static void main(String a[]){ String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"}; List<String> strList = Arrays.asList(strArr); System.out.println("Created List Size: "+strList.size()); System.out.println(strList); } } Program: How to find or search array elements by binary search? package com.java2novice.arrays; import java.util.Arrays; public class BinarySearchOnCharArray { public static void main(String a[]){ char[] chrArr = {'a','c','d','y','e','q','b'}; int index = Arrays.binarySearch(chrArr, 0, chrArr.length-1, 'q'); System.out.println("Char 'q' index is: "+index); } } Program: How to copy array and increase size dynamically? package com.java2novice.arrays; import java.util.Arrays; public class MyArrayCopy { public static void main(String a[]){ int[] myArr = {2,4,2,4,5,6,3}; System.out.println("Array size before copy: "+myArr.length); int[] newArr = Arrays.copyOf(myArr, 10); System.out.println("New array size after copying: "+newArr.length); } } Program: How to copy range of elements from an array? package com.java2novice.arrays; import java.util.Arrays; public class MyArrayRangeCopy { public static void main(String a[]){ int[] myArr = {2,4,2,4,5,6,3}; System.out.println("My array elements:\n"); for(int num:myArr){ System.out.print(num+" "); } int[] newArr = Arrays.copyOfRange(myArr, 1, 4); System.out.println("\nMy new array elements:\n"); for(int num:newArr){ System.out.print(num+" "); } } } Program: How to compare two arrays and confirm they are equal?

Page 17 of 26

package com.java2novice.arrays; import java.util.Arrays; public class MyArrayDeepEquals {

Java Programs

Page 18 of 26

public static void main(String a[]){ String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"}; String[] strArrCopy = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"}; System.out.println("Are strArr and strArrCopy same? " +Arrays.deepEquals(strArr, strArrCopy)); String[] strArrMod = {"JAVA", "C++", "PERL", "STRUTS"}; System.out.println("Are strArr and strArrMod same? " +Arrays.deepEquals(strArr, strArrMod)); } } Program: How to fill an array with default values? package com.java2novice.arrays; import java.util.Arrays; public class MyArrayFill { public static void main(String a[]){ String[] myArr = new String[10]; Arrays.fill(myArr, "Assigned"); for(String str:myArr){ System.out.println(str); } } } Program: How to sort an array? package com.java2novice.arrays; import java.util.Arrays; public class MyArraySort { public static void main(String a[]){ int[] myArr = {3,2,56,12,98,23,56}; Arrays.sort(myArr); for(int str:myArr){ System.out.println(str); } } } Program: How to sort an array using comparator? package com.java2novice.arrays; import java.util.Arrays; import java.util.Comparator; public class MyStringArraySorting { public static void main(String a[]){ String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};

Arrays.sort(strArr,new Comparator<String>(){ @Override public int compare(String o1, String o2) { return o1.compareTo(o2); }}); for(String str:strArr){ System.out.println(str); } } } Output: C++ JAVA PERL PLAY STRUTS Java Enum Examples Description: Few points about enum types are:

Java Programs

Page 19 of 26

they are implicitly final subclasses of java.lang.Enum. Enum constants are by default public static final fields. If you declare Enum is a member of your class, then by default it is static. We should not use new operator with enum type at anytime. Program: Basic Enum example. Description: This example defines a basic enum type called Fruits. It contains few constants representing fruits. The switch case uses these constants to execute conditions. package com.java2novice.enums; public class MyBasicEnum { private Fruits myFruit; public MyBasicEnum(Fruits fruit){ this.myFruit = fruit; } public void getFruitDesc(){ switch (myFruit) { case GRAPE: System.out.println("A grape is a non-climacteric fruit."); break; case APPLE: System.out.println("The apple is the pomaceous fruit."); break; case MANGO: System.out.println("The mango is a fleshy stone fruit."); break; case LEMON: System.out.println("Lemons are slow growing varieties of citrus."); break; default: System.out.println("No desc available."); break;

} }

Java Programs

Page 20 of 26

public static void main(String a[]){ MyBasicEnum grape = new MyBasicEnum(Fruits.GRAPE); grape.getFruitDesc(); MyBasicEnum apple = new MyBasicEnum(Fruits.APPLE); apple.getFruitDesc(); MyBasicEnum lemon = new MyBasicEnum(Fruits.LEMON); lemon.getFruitDesc(); MyBasicEnum guava = new MyBasicEnum(Fruits.GUAVA); guava.getFruitDesc(); } } enum Fruits { GRAPE, APPLE, MANGO, LEMON,GUAVA } Output: A grape is a non-climacteric fruit. The apple is the pomaceous fruit. Lemons are slow growing varieties of citrus. No desc available.

Program: How to call enum, which is defined inside a class? Description: This example defines a basic enum type called Fruit inside a class. This example shows how to call enum constants defined under another class. If you declare Enum is a member of a class, then by default it is static. You can access it with reference to enclosing class. package com.java2novice.enums; public class MyEnumInsideClass { private MyWrapper.Fruit myFruit; public MyEnumInsideClass(MyWrapper.Fruit fruit){ this.myFruit = fruit; } public void getFruitDesc(){ switch (myFruit) { case GRAPE: System.out.println("A grape is a non-climacteric fruit."); break; case APPLE: System.out.println("The apple is the pomaceous fruit."); break; case MANGO: System.out.println("The mango is a fleshy stone fruit."); break; case LEMON: System.out.println("Lemons are slow growing varieties of citrus."); break; default: System.out.println("No desc available."); break; }

Java Programs

Page 21 of 26

public static void main(String a[]){ MyEnumInsideClass grape = new MyEnumInsideClass(MyWrapper.Fruit.GRAPE); grape.getFruitDesc(); MyEnumInsideClass apple = new MyEnumInsideClass(MyWrapper.Fruit.APPLE); apple.getFruitDesc(); MyEnumInsideClass lemon = new MyEnumInsideClass(MyWrapper.Fruit.LEMON); lemon.getFruitDesc(); MyEnumInsideClass guava = new MyEnumInsideClass(MyWrapper.Fruit.GUAVA); guava.getFruitDesc(); } } class MyWrapper{ enum Fruit { GRAPE, APPLE, MANGO, LEMON,GUAVA } } Output: A grape is a non-climacteric fruit. The apple is the pomaceous fruit. Lemons are slow growing varieties of citrus. No desc available.

Program: How to override toString() method with enum? package com.java2novice.enums; public class MyEnumtoString { enum Fruit { GRAPE{ public String toString(){ return "A grape is a non-climacteric fruit."; } }, APPLE{ public String toString(){ return "The apple is the pomaceous fruit."; } }, MANGO{ public String toString(){ return "The mango is a fleshy stone fruit."; } }, LEMON{ public String toString(){ return "Lemons are slow growing varieties of citrus."; } } } public static void main(String a[]){ System.out.println(Fruit.GRAPE); System.out.println(Fruit.APPLE); System.out.println(Fruit.MANGO); } } Output: A grape is a non-climacteric fruit. The apple is the pomaceous fruit. The mango is a fleshy stone fruit.

Java Programs
Program: How to create custom constructor enum? package com.java2novice.enums; public class MyEnumCustomConstructor { enum Department{ ACCOUNT(12),HR(24),FINANCE(100),SECURITY(108); private int deptId; Department(int id){ deptId = id; } public int getDeptId(){ return deptId; } } public static void main(String a[]){ System.out.println("Accounts dept id:"+Department.ACCOUNT.getDeptId()); System.out.println("HR dept id:"+Department.HR.getDeptId()); System.out.println("Security dept id:"+Department.SECURITY.getDeptId()); } } Output: Accounts dept id:12 HR dept id:24 Security dept id:108

Page 22 of 26

Java Integer Wrapper Class Program: How to create int to Integer object? package com.java2novice.wrapper.integer; public class MyBasicInteger { public static void main(String a[]){ int i = 10; Integer intg = new Integer(i); System.out.println(intg); String no = "223"; Integer num = new Integer(no); System.out.println(num); } } 10 223 Program: How to convert Integer to primitive types? package com.java2novice.wrapper.integer; public class MyIngegerByteValue { public static void main(String a[]){ Integer itr = new Integer(10); System.out.println("byte value: "+itr.byteValue()); System.out.println("double value: "+itr.doubleValue());

System.out.println("float value: "+itr.floatValue()); System.out.println("int value: "+itr.intValue()); System.out.println("long value: "+itr.longValue()); System.out.println("short value: "+itr.shortValue()); } } Output: byte value: 10 double value: 10.0 float value: 10.0 int value: 10 long value: 10 short value: 10 Program: How to get Integer maximum and minimum value? package com.java2novice.wrapper.integer; public class MyIntegerMaxMinValue { public static void main(String a[]){ System.out.println("Integer Max Value: "+Integer.MAX_VALUE); System.out.println("Integer Min Value: "+Integer.MIN_VALUE); } } Output: Integer Max Value: 2147483647 Integer Min Value: -2147483648 Program: How to convert String to Integer value? package com.java2novice.wrapper.integer; public class MyStringToInteger { public static void main(String a[]){ String str = "23"; Integer i = Integer.valueOf(str); System.out.println("The integer value: "+i); } } Output: The integer value: 23 How do I sort a list with multiple sort parameters? public class Person { private int id; private String name, address; public static Comparator<Person> getComparator(SortParameter... sortParameters) { return new PersonComparator(sortParameters); } public enum SortParameter { ID_ASCENDING, ID_DESCENDING, NAME_ASCENDING, NAME_DESCENDING, ADDRESS_ASCENDING, ADDRESS_DESCENDING

Java Programs

Page 23 of 26

Java Programs

Page 24 of 26

private static class PersonComparator implements Comparator<Person> { private SortParameter[] parameters; private PersonComparator(SortParameter[] parameters) { this.parameters = parameters; } public int compare(Person o1, Person o2) { int comparison; for (SortParameter parameter : parameters) { switch (parameter) { case ID_ASCENDING: comparison = o1.id - o2.id; if (comparison != 0) return comparison; break; case ID_DESCENDING: comparison = o2.id - o1.id; if (comparison != 0) return comparison; break; case NAME_ASCENDING: comparison = o1.name.compareTo(o2.name); if (comparison != 0) return comparison; break; case NAME_DESCENDING: comparison = o2.name.compareTo(o1.name); if (comparison != 0) return comparison; break; case ADDRESS_ASCENDING: comparison = o1.address.compareTo(o2.address); if (comparison != 0) return comparison; break;

case ADDRESS_DESCENDING:

Java Programs

Page 25 of 26

comparison = o2.address.compareTo(o1.address); if (comparison != 0) return comparison; break; } } return 0; } } }//

package de.vogella.algorithms.sort.standardjava; import java.util.Comparator; public class MyIntComparable implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return (o1>o2 ? -1 : (o1==o2 ? 0 : 1)); } } package de.vogella.algorithms.sort.standardjava; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Simple2 { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(4); list.add(3); list.add(7); list.add(2); list.add(1); Collections.sort(list, new MyIntComparable());

for (Integer integer : list) { System.out.println(integer); } }}

Java Programs

Page 26 of 26

S-ar putea să vă placă și