So this program is attempted to take a command line argument like the following:
S 4 1 2 3 4 4
args[0] is the array type
args[1] is the array length
args[2...] are the values in the array
args[length-1] is a key that will be used in a linear search
public class whatTheFoo{
#SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> void main(String[] args) {
for(int i=0;i<args.length;i++)System.out.print(args[i]);
System.out.println();
int arraySize = Integer.parseInt(args[1]);
E[] array = (E[])new Object[arraySize];
E key = null;
if (args[0].matches("I|i")) {
for (int i = 2; i < args.length-1; i++) {
array[i-2]=(E)new Integer(args[i]);
System.out.println(array[i-2]);
}
key = (E) new Integer(args[args.length-1]);
System.out.println("Key is: " + key);
}
...
if(linearSearch(array, key)<0)
System.out.println("Didnt find it");
else
System.out.println("Found it at index: "+(linearSearch(array, key)-1));
}
public static <E> int linearSearch(E[]array,E key) {
int index=-1;
for(int i=0;i<array.length;i++) {
if(array[i].equals(key)){
index = (int) array[i];
}
}
return index;
}
}
This works, but when I change the linearSearch method to:
public static <E extends Comparable<E>> int linearSearch(E[]array,E key)
I get the error message:
The method linearSearch(E[], E extends Comparable<E>) in the type Prog7b is not applicable for the arguments (E[], E)
but if I change main to:
public static <E extends Comparable<E>> void main(String[] args) {
I get:
Exception in thread "main" I412344java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at whatTheFoo.main(whatTheFoo.java:10)
The method has been directed to include in the method:
<E extends Comparable<E>>.
Where am I going wrong? Thanks for reading.
-------------------------------------------------------------------
For those that may be curious, this is the end result of all the help supplied. Thanks again!
public class Prog7b {
// #SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
if (args[0].matches("I|i")) {
Integer[] array = new Integer[Integer.parseInt(args[1])];
for (int i = 2; i < args.length - 1; i++) {
array[i - 2] = new Integer(args[i]);
}
Integer key = new Integer(args[args.length - 1]);
if (linearSearch(array, key) < 0) {
System.out.println("Didnt find it");
} else
System.out.println("Found it at index: " + (linearSearch(array, key) - 1));
System.out.println("The max of the array is: " + max(array));
print(array);
} else if (args[0].matches("S|s")) {
String[] array = new String[Integer.parseInt(args[1])];
for (int i = 2; i < args.length - 1; i++) {
array[i - 2] = new String(args[i]);
}
String key = new String(args[args.length - 1]);
if (linearSearch(array, key) < 0) {
System.out.println("Didnt find it");
} else
System.out.println("Found it at index: " + (linearSearch(array, key) - 1));
System.out.println("The max of the array is: " + max(array));
print(array);
} else {
Double[] array = new Double[Integer.parseInt(args[1])];
for (int i = 2; i < args.length - 1; i++) {
array[i - 2] = new Double(args[i]);
}
Double key = new Double(args[args.length - 1]);
if (linearSearch(array, key) < 0) {
System.out.println("Didnt find it");
} else
System.out.println("Found it at index: " + (linearSearch(array, key) - 1));
System.out.println("The max of the array is: " + max(array));
print(array);
}
}
public static <E extends Comparable<E>> int linearSearch(E[] array, E key) {
int index = 0;
for (int i = 0; i < array.length; i++) {
index++;
if (array[i].equals(key)) {
return index;
}
}
return -1;
}
public static <E extends Comparable<E>> E max(E[] list) {
E max = list[0];
for (int i = 1; i < list.length; i++) {
if (max.compareTo(list[i]) < 0) {
max = list[i];
}
}
return max;
}
private static <E> void print(E[] list) {
System.out.print("[");
for (int i = 0; i < list.length - 1; i++)
System.out.print(list[i] + ", ");
System.out.print(list[list.length - 1] + "]\n");
}
}
I don't think main is supposed to be generic. (The <E> part in the method declaration declares a type variable, which makes it generic.) If main is really supposed to be generic, then you need to talk to your teacher because they are doing something weird and we can't really guess about it.
Generics are a compile-time only concept. Basically the idea is that you have some code which is actually somewhat agnostic about particular types, but still need some kind of abstract information about it.
For example, suppose we had some method that checks if an object is null:
Object requireNonNull(Object obj) {
if (obj == null) {
throw new NullPointerException();
} else {
return obj;
}
}
This is fine. We can pass any sort of object to the method. (Integer, String, whatever.) But what if we wanted to assign the return value directly?
We want to be able to do this:
String mightBeNull = ...;
String definatelyNotNull = requireNonNull(mightBeNull);
This makes our validation code neater. (Maybe instead of checking for null, our validation is actually about 10 lines long and we don't want to repeat it all the time.)
Well, as it stands, we can't, because we will get a compile-time error for trying to assign an Object to a String.
Generics let us do this, though:
<T> T requireNonNull(T obj) {
if (obj == null) {
throw new NullPointerException();
} else {
return obj;
}
}
The type parameter <T> says that we declare a sort of temporary type. We don't care about what it actually is, but we can say that the method returns whatever we pass to it. Whatever type obj is at the point that we call requireNonNull, the method returns that type to the caller.
So now we can do this:
String s = requireNonNull("");
Integer i = requireNonNull(10);
Float f = requireNonNull(2f);
And so on.
requireNonNull is actually a real method and that is how it works.
The point, though, is that generics let you write very general API which gets called by non-generic code.
For your assignment it looks like you're supposed to write a generic method linearSearch with a bounded type parameter <E extends Comparable<E>> (essentially meaning that whatever array type you pass to linearSearch, it has to be some subtype of Comparable). Then you're probably supposed to pass it different types of arrays in main, like Integer[], String[], etc. Your main method won't be generic. You'll just have an if...else if chain for each type that args[0] requires.
Related
So basically my code is doing what the question says. In the way the code is laid out now it gives the correct results, but when I change the order of the .add pieces of code it gives different results each time. I feel the compareTo method is fine, but am i missing something? I'm trying to get the smallest result.
Thanks in advance.
package lists;
import java.util.*;
public class Lab4 {
public static <T extends Comparable> int smallest(List<T> l) {
if (l.size() == 0)
return -1;
else {
Iterator<T> it = l.iterator();
T smallestSoFar = it.next();
T temp;
int smallestPos = 0;
int i = 0; //used to indicate position in list of next item
while (it.hasNext()) {
temp = it.next();
if (temp.compareTo(smallestSoFar) > 0) {
smallestSoFar = temp;
smallestPos++;
}
i++;
}
return smallestPos;
}
}
public static <T extends Comparable> void deleteSmallest(List<T> l) { // for exercise 3
}
public static void main(String[] args) {
Vector<String> vec1 = new Vector<String>();
vec1.add("Hello");
vec1.add("xxxx");
vec1.add("world");
vec1.add("aardvark");
int smallPos = smallest(vec1);
if (smallPos != -1)
System.out.println("smallest entry is " + vec1.elementAt(smallPos) + " at position " + smallPos);
Vector<Integer> vec2 = new Vector<Integer>();
vec2.add(new Integer(47));
vec2.add(new Integer(247));
vec2.add(new Integer(17));
vec2.add(new Integer(399));
smallPos = smallest(vec2);
if (smallPos != -1)
System.out.println("smallest entry is " + vec2.elementAt(smallPos) + " at position " + smallPos);
}
}
Your comparison test is the wrong way around. Currently you're picking the largest value.
if (temp.compareTo(smallestSoFar) > 0) {
Should be
if (temp.compareTo(smallestSoFar) < 0) {
Also, smallestPos++;should be smallestPos=i;
Currently you're returning a count of the number of times the "smallest" value changed.
With java8 you can make your smallest() method more compact:
public static <T extends Comparable<T>> int smallest( List<T> list ){
return list.stream() // get Stream<T> from list
.sorted(Comparable::compareTo) // Stream<T> is now sorted
.mapToInt(list::indexOf) // maps Stream<T> to an IntStream consisting of indices
.findFirst() // find the first value (the smallest)
.orElse(-1); // if nothing found, hence list was empty, then return -1
}
and when i tested it with my function there were no inconsistencies
I am trying to make a program that creates an ArrayList given the type as well as the values that will be put into the ArrayList. The input structure that we have to work with is "I 6 7 5 3 1 -1 2" with the I being the type Integer (or S for String, etc) and the first number (6) being how many values are in the ArrayList. I'm not sure how to instantiate the ArrayList.
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String type = scan.next();
int length = scan.nextInt();
int counter = 0;
if (type.equals("I")) {
ArrayList<Integer> A = new ArrayList<Integer>;
}
else if (type.equals("S")) {
ArrayList<String> A = new ArrayList<String>;
}
else if (type.equals("D")) {
ArrayList<Double> A = new ArrayList<Double>;
}
else {
System.out.println("Invalid type");
}
while (scan.hasNext() && counter<length) {
String s1 = scan.next();
A.add(s1);
counter += 1;
}
System.out.print(A);
}
//Removes any duplicate values in the arraylist by checking each value after it
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
ArrayList<E> inArray = list;
for (int i = 0; i<inArray.size(); i++) {
for (int j = i+1; j<inArray.size(); j++) {
if (inArray.get(i) == inArray.get(j)) {
inArray.remove(j);
}
}
}
return inArray;
}
//Shuffles the contents of the array
public static <E> void shuffle(ArrayList<E> list) {
E temp;
int index;
Random random = new Random();
for (int i = list.size()-1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = list.get(index);
list.set(index, list.get(i));
list.set(i, temp);
}
System.out.print(list);
return;
}
//Returns the largest element in the given arraylist
public static <E extends Comparable<E>> E max(ArrayList<E> list) {
E max = Collections.max(list);
System.out.println(max);
return max;
}
I cannot in good conscious give you the answer you want, but rather I'll give you the answer you need.
DON'T DO THAT!
It serves no purpose at all. Datatype erasure at compile time of generics makes the ArrayList<Whatever> act equivalently to ArrayList<?> You cannot ascertain the generic type during runtime unless you type check the elements within the ArrayList
You might as well write this code, it'll give you the same exact results:
public static ArrayList<?> returnProper(String type) {
if(type.length() == 1 && "ISD".contains(type)) {
return new ArrayList();
} else {
System.out.println("Invalid type");
return null;
}
}
THUS, PLEASE DON'T DO THAT
Replace the second E with an "?" and then fix the method to return.
public static <T> ArrayList<?> returnProper(String type) {
if (type.equals("I")) {
return new ArrayList<Integer>();
} else if (type.equals("S")) {
return new ArrayList<String>();
} else if (type.equals("D")) {
return new ArrayList<Double>();
} else {
System.out.println("Invalid type");
}
return null;
}
This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 7 years ago.
This is an array based Queue , for int :
/**
* Array based
* #author X220
*
*/
public class MyQueue {
private int[] _data;
private int MAX_SIZE;
private int front = -1;
private int back = 0;
private int elementsCount = 0;
public void printQueue()
{
int j = this.front + 1;
int i = 0;
while (i < this._data.length && i < elementsCount)
{
System.out.println("At location " + j % MAX_SIZE + " element :" + this._data[j % MAX_SIZE]);
j++;
i++;
}
}
public MyQueue(int _size)
{
MAX_SIZE = _size > 0 ? _size : 10;
this._data = new int[MAX_SIZE];
}
public boolean IsEmpty()
{
return this.elementsCount == 0;
}
public boolean IsFull()
{
return this.elementsCount == MAX_SIZE;
}
public void Push(int pushMe) throws QueueIsFullException
{
if (IsFull())
{
throw new QueueIsFullException("Queue is full");
}
this.elementsCount++;
_data[back++ % MAX_SIZE] = pushMe;
}
public int Pop() throws QueueIsEmptyException
{
if (IsEmpty())
{
throw new QueueIsEmptyException("Queue is full");
}
elementsCount--;
return _data[++front % MAX_SIZE];
}
public static void main(String args[])
{
try
{
MyQueue q1 = new MyQueue(15);
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
q1.Push(5);
q1.Pop();
q1.Pop();
q1.Pop();
q1.Pop();
q1.Pop();
q1.Push(6);
q1.Pop();
q1.Push(7);
q1.Push(8);
q1.Push(9);
q1.Push(10);
q1.Push(11);
q1.Push(12);
// q1.Push(1);
// q1.Push(2);
// q1.Push(3);
// q1.Push(4);
// q1.Push(5);
// q1.Push(7);
// q1.Push(8);
// q1.Push(9);
// q1.Push(10);
// q1.Push(11);
// q1.Push(12);
// q1.Push(40);
// q1.Push(50);
q1.printQueue();
}
catch (Exception e)
{
System.out.println(e);
}
}
#SuppressWarnings("serial")
class QueueIsFullException extends Exception
{
public QueueIsFullException(String message){
super(message);
}
}
#SuppressWarnings("serial")
class QueueIsEmptyException extends Exception
{
public QueueIsEmptyException(String message){
super(message);
}
}
}
I wanted to use generics so I changed the int to T but then I got for this :
public class MyQueue <T>{
private T[] _data;
private int MAX_SIZE;
private int front = -1;
private int back = 0;
private int elementsCount = 0;
public void printQueue()
{
int j = this.front + 1;
int i = 0;
while (i < this._data.length && i < elementsCount)
{
System.out.println("At location " + j % MAX_SIZE + " element :" + this._data[j % MAX_SIZE]);
j++;
i++;
}
}
public MyQueue(int _size)
{
MAX_SIZE = _size > 0 ? _size : 10;
this._data = new T[MAX_SIZE];
}
....
}
That :
Cannot create a generic array of T
And from the answers to this post I see that I can't use generics with arrays .
Does this mean that there is no work around for a generics Queue based on array ? Must I switch to some other data structure ?
The root cause of your problem is not with your MyQueue class, I think you misunderstand the way Java handles generics. Generic types exist only at compile time, after that they are simply erased from the byte code and at runtime only real Java types exist behind the scenes.
This is why you cannot instantiate a generic type, because at runtime this parameterized type simply doesn't exist.
What you can do is to provide a real class (extending T) as a parameter in your MyQueue class an instantiate this class type, since this is a first-class Java type.
Here is a very similar StackOverflow question and a solution:
Instantiating a generic class in Java
It is also recommended to read the Java reference about generics, like the answer for you original question is here:
https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects
No there is a work around for this the ugly cast, change your array generic creation to:
this._data = (T[])new Object[MAX_SIZE];
Due to the implementation of Java generics, you can't have code like this:
this._data = new T[MAX_SIZE];
Have a look at this How to create a generic array in Java?
The method I prefer is using
#SuppressWarnings("unchecked")
T[] arr = (T[]) Array.newInstance(clazz,length);
where clazz is the Class<T> object corresponding to the generic type. Note that the cast is unchecked, but Array.newInstance ensures you that you won't be able to insert invalid types into your array.
To me this is the best solution because :
you handle the type consistency to the Array class by passing a Class<T> instance which will be used to cast all the objects inserted in the array. This is thus type-safe without needing you to do anything.
this is relatively small and self-contained, it won't force you to manually cast objects over and over everytime you use the array. This would be the case if you were using an Object[] under the hood.
format: get(index):Object.
public class MyArrayList {
public String[] arrays = {};
public MyArrayList() {
arrays = new String[10];
}
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
}
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
With this code it prints out:
Testing constructor, add(object) and size()
The zoo now holds 10 animals: 0 1 2 3 4 5 6 7 8 9
Obviously my code for get method is very wrong but instead of printing out the numbers it should print out "Ant","Bison,"Camel" etc.
All help appreciated for code as I'm a very new programmer. Thanks.
Fixing your Get Method
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
Okay, so let's look at this shall we? There's a few values that the user can provide..
i < 0
0 < i < size of array <-- The only valid one.
i > size of array
So first you need to check for that!
if(i > 0 && i < arrays.length) {
// This is a valid index!
}
Okay, so you know it's a valid index. Step two is retrieving the value..
return arrays[i];
And finally, the return type needs to be set. At the moment it is int. It needs to be String in this example..
public String get(int i)
It's that simple! When you call printZoo(), you'll see the values and not their indices.
Onto your Objects
You can have an array of type Object without importing any classes. This will change arrays of type String[] to..
Object[] arrays;
Your Code is technically correct, but if you want to return string values in run time, you must change the value returned in method get to String as in
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
to
public String get(int i){
return arrays[i];
}
Also in your method printZoo(), you have another loop, so i'd imagine your code printing out duplicate values. so why don't you have the printZoo Method dealing with the for loop and the get() method above displaying the values
So Change your get method to the one i have here, and everything should work for you
If it doesn't Work, then try these pieces of Code
MyArrayList.java
public class MyArrayList{
public String[] arrays = {};
public int i = 0;
public MyArrayList() {
arrays = new String[10];
}
public void add(String a)throws ListFullException{ //Add to List if Arraylist is not full
if(i != arrays.length-1){
arrays[i] = a;
i++;
}
else{
throw new ListFullException("List Full");
}
}
public String get(int i){
return arrays[i];
}
public int getArraySize(){
return arrays.length;
}
}
MyArrayListTest.java
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.getArraySize() + " animals: ");
for (int j = 0; j < zoo.getArraySize(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
And the Exceptions class
ListFullException.java
public class ListFullException extends RuntimeException{
public ListFullException(String m){
super(m);
}
}
I hope this will be a great study tool for you, if you feel this has helped you, upvote and accept :) :P
It is printing an int because you are calling zoo.get(j) and get() returns ints:
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
You need to return a String, something along the lines of:
public String get(int i){
return arrays[i];
}
I am trying to implement a generic selection sort which can take any objects and do the sorting on it. I can promise to the compiler that whatever objects I am comparing, has the compareTo method implemented for it. But I get compile error for the following code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SelectionSortGenerics implements Comparable<E> {
private <E> void swap(E[] a, int i, int j) {
if (i != j) {
E temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public <E> void selectionSort(E[] a) {
for (int i = 0; i < a.length - 1; i++) {
// find index of smallest element
int smallest = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[smallest])<=0) {
smallest = j;
}
}
swap(a, i, smallest); // swap smallest to front
}
}
public static void main(String[] args){
SelectionSortGenerics firstsort = new SelectionSortGenerics();
Integer[] arr = {3,4,1,5};
System.out.println("before sorting int: "+ Arrays.toString(arr));
firstsort.selectionSort(arr);
System.out.println("After sorting int : "+Arrays.toString(arr));
String[] arr1= {"acd","ded","dal","bad","cle"};
System.out.println("before sorting String: "+ Arrays.toString(arr1));
firstsort.selectionSort(arr1);
System.out.println("After sorting String : "+Arrays.toString(arr1));
Character[] arr2= {'c','e','a','d','c'};
System.out.println("before sorting char: "+ Arrays.toString(arr2));
firstsort.selectionSort(arr2);
System.out.println("After sorting char : "+Arrays.toString(arr2));
}
}
As you can see, the objects I am passing in main method are Integer, String and Character, which has compareTo methods. how would make the above code work. Anywhere, casting is needed?
Thanks for your help.
The following works for me. All I did was remove the <E> in the class declaration and changed <E> to <E extends Comparable<E>> in selectionSort.
The generic <E> in the class declaration is unnecessary and potentially confusing since your class doesn't actually need to be generic. Only the methods in the class are generic, not the class itself.
Second, the selectionSort method requires the element type passed in to be comparable to itself. You can represent this by E extends Comparable<E>.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SelectionSortGenerics {
private <E> void swap(E[] a, int i, int j) {
if (i != j) {
E temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public <E extends Comparable<E>> void selectionSort(E[] a) {
for (int i = 0; i < a.length - 1; i++) {
// find index of smallest element
int smallest = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[smallest])<=0) {
smallest = j;
}
}
swap(a, i, smallest); // swap smallest to front
}
}
public static void main(String[] args){
SelectionSortGenerics firstsort = new SelectionSortGenerics();
Integer[] arr = {3,4,1,5};
System.out.println("before sorting int: "+ Arrays.toString(arr));
firstsort.selectionSort(arr);
System.out.println("After sorting int : "+Arrays.toString(arr));
String[] arr1= {"acd","ded","dal","bad","cle"};
System.out.println("before sorting String: "+ Arrays.toString(arr1));
firstsort.selectionSort(arr1);
System.out.println("After sorting String : "+Arrays.toString(arr1));
Character[] arr2= {'c','e','a','d','c'};
System.out.println("before sorting char: "+ Arrays.toString(arr2));
firstsort.selectionSort(arr2);
System.out.println("After sorting char : "+Arrays.toString(arr2));
}
}
**Refer below method to implement generic sorting.You just have to pass list in sortElements and the name of the field on you want to enable sorting**
/**
* This method is used to sort the elements based on the fieldName specified.
* Sorting order is Ascending order.
*
* #param resultList
* e.g., List of ProductBrand
* #param fieldName
* e.g., productBrandName list will be sorted according to this
* fieldName.
* #throws Exception
*/
public static <Type> void sortElements(List<Type> resultList, final String fieldName, final boolean isDesc) throws Exception
{
Collections. sort(resultList, new Comparator<Type>()
{
#Override
public int compare(Type o1, Type o2)
{
return compareValue(o1, o2);
}
private int compareValue(Type o1, Type o2)
{
int returnValue = 0;
try
{
Field field = o1.getClass().getDeclaredField(fieldName);
boolean accessible = field.isAccessible();
field.setAccessible( true);
Object objectO1 = field.get(o1);
Object objectO2 = field.get(o2);
if (objectO1 instanceof Number)
{
if ((objectO1 != null && objectO2 != null)
&& (objectO1 instanceof Integer || objectO1 instanceof Long || objectO1 instanceof Byte))
{
returnValue = Long.valueOf(objectO1 + "").compareTo(Long. valueOf(objectO2 + ""));
}
else if ((objectO1 != null && objectO2 != null) && (objectO1 instanceof Double || objectO1 instanceof Float))
{
returnValue = Double.valueOf(objectO1 + "").compareTo(Double. valueOf(objectO2 + ""));
}
}
else if (objectO1 instanceof String || objectO1 instanceof Character)
{
if ((objectO1 != null) && objectO2 != null)
{
returnValue = normalizedString(String.valueOf(objectO1)).compareToIgnoreCase(
normalizedString(String.valueOf(objectO2)));
}
}
field.setAccessible(accessible);
}
catch (Exception e)
{
System. out.println("Error occured while sorting elements");
}
if (isDesc)
{
if (returnValue > 0)
{
return -1;
}
else if (returnValue < 0)
{
return 1;
}
}
return returnValue;
}
});
}
/**
* This methods Normalizes the input string. Here we remove accent from the
* character so that we can sort the string properly using normal characters.
*
* #param str
* example <B> BSH Electrodom�sticos Espa�a S.A. </b>
* #return Normalized String . <B> ex : BSH Electrodomesticos Espana S.A.</b>
*
*/
public static String normalizedString(String str)
{
if (!isNullOrBlank(str))
{
String nfdNormalizedString = Normalizer. normalize(str, Normalizer.Form.NFD );
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(nfdNormalizedString).replaceAll("");
}
else
{
return "" ;
}
}
/**
* This function checks that the value is blank or null.
*
* #param value
* value to be checked
* #return true if value is blank or null
*/
public static boolean isNullOrBlank(String value)
{
boolean retFlag = false;
if (value == null || value.trim().equals("") || value.trim().equals("null" ))
{
retFlag = true;
}
return retFlag;
}
Note: The sorting algorithm implemented below works only for an array of the length of a power of two. You can use this technique for other sorting algorithms too:
Approach 1: Using java.util.Comparator
Approach 2:Using T extends Comparable
Main Method:Main method