Call an object from a map and cast directly - java

private static final Map<Integer, GameObject> OBJECT = new ConcurrentHashMap<>();
I have a map in which I store GameObjects, which is extended by PlayerObject, NpcObject, ItemObject.
I'm trying to create a method on which I call the object by ID and class type and cast at it directly and if it's not exists or the class of the object ID does not match the given one to return null.
So for example
final PlayerObject object = getObject(<id>, PlayerObject);
Is there any way?
Edit:
I managed to do this:
public <T extends EventObject> T getObject(final int objectId)
{
final EventObject object = OBJECT.get(objectId);
return Objects.nonNull(object) && object.getClass() == ? T (object) : null;
}
But i don't want to use Class<? extends EventObject> in parameter of this method. Can't i somehow check using the generic T if it's the same class to cast it and return or else null?

You can use Class#isInstance to check if the object's type is correct and Class#cast to convert the object to the correct type.
public static <T extends GameObject> T getObject(Integer id, Class<T> clazz) {
GameObject obj = OBJECT.get(id);
if(!clazz.isInstance(obj)) return null;
return clazz.cast(obj);
}
// ...
final PlayerObject object = getObject(<id>, PlayerObject.class);

try this complete generic method:
public static <T> T getObject(int id, Class<T> c){
Object object = OBJECT.get(id);
return object != null && object.getClass() == c ? c.cast(object) : null;
}
The other parts of the program:
private static final Map<Integer, GameObject> OBJECT = new ConcurrentHashMap<>();
public static void main(String[] args) throws ParseException {
init();
PlayerObject p = getObject(3, PlayerObject.class);
ItemObject i = getObject(3, ItemObject.class);
PlayerObject p2 = getObject(4, PlayerObject.class);
System.out.println(p);
System.out.println(i);
System.out.println(p2);
}
private static void init() {
OBJECT.put(1, new PlayerObject(1, "SomePlayer1"));
OBJECT.put(2, new PlayerObject(2, "SomePlayer2"));
OBJECT.put(3, new ItemObject(3, 5));
OBJECT.put(4, new ItemObject(4, 7));
}
GameObject.class
public class GameObject {
protected int id;
GameObject(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
PlayerObject.class
public class PlayerObject extends GameObject {
private String playerName;
PlayerObject(int id, String playerName) {
super(id);
this.playerName = playerName;
}
public String getPlayerName() {
return this.playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
#Override
public String toString() {
return "PlayerObject{\"id\": " +
this.id +
", \"playerName\": \"" +
this.playerName +
"\"}";
}
}
ItemObject.class
public class ItemObject extends GameObject {
private int itemCount;
ItemObject(int id, int itemCount) {
super(id);
this.itemCount = itemCount;
}
public int getItemCount() {
return this.itemCount;
}
public void setItemCount(int itemCount) {
this.itemCount = itemCount;
}
#Override
public String toString() {
return "ItemObject{\"id\": " +
this.id +
", \"itemCount\": " +
this.itemCount +
"}";
}
}
And the output of the program:
PlayerObject{"id": 1, "playerName": "SomePlayer1"}
ItemObject{"id": 3, "itemCount": 5}
null

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public class Stackoverflow_68734414 {
private static Map<Integer, GameObject> OBJECT_MAP = new ConcurrentHashMap<>();
public static void main(String[] args) {
PlayerObject po = new PlayerObject();
ItemObject io = new ItemObject();
OBJECT_MAP.put(1, po);
OBJECT_MAP.put(2, io);
PlayerObject p1 = getObject(1, PlayerObject.class);
PlayerObject p2 = getObject(2, PlayerObject.class);
ItemObject i1 = getObject(1, ItemObject.class);
ItemObject i2 = getObject(2, ItemObject.class);
System.out.println(p1);
System.out.println(p2);
System.out.println(i1);
System.out.println(i2);
}
public static <T extends GameObject> T getObject(Integer id, Class<T> klass){
GameObject object = OBJECT_MAP.get(id);
if(Objects.nonNull(object) && (object.getClass() == klass)) {
return klass.cast(object);
} else{
return null;
}
}
}
class GameObject{
}
class PlayerObject extends GameObject {
}
class ItemObject extends GameObject{
}
Output is as expected:
PlayerObject#179d3b25
null
null
ItemObject#254989ff

Are you looking for something similar to this:
public boolean isItemObject(int id){
GameObject obj = OBJECT.get(id)
if(obj instanceof ItemObject && obj != null){
return true;
}
return false;
}
public boolean isPlayerObject(int id){
GameObject obj = OBJECT.get(id)
if(obj instanceof PlayerObject && obj != null){
return true;
}
return false;
}
public boolean isNPCObject(int id){
GameObject obj = OBJECT.get(id)
if(obj instanceof NpcObject && obj != null){
return true;
}
return false;
}
//...
final PlayerObject pObject = isPlayerObject(objectID) ? OBJECT.get(id) : null;

Related

Stuck in generics

I've a base class BaseNewsItem, and 2 derived classes NewsItem and MovieNewsItem. Then, there's a MovieListingFeed class which holds a list of MovieNewsItem and is parcelable. It can parcel this list as and when required by any activity.
protected MovieNewsListingFeed(Parcel in) {
this.pg = in.readParcelable(PageDetail.class.getClassLoader());
this.items=new ArrayList<>();
in.readTypedList(items, MovieNewsItem.CREATOR);
}
I receive an error at the line :
in.readTypedList(items, MovieNewsItem.CREATOR);
Error:
Error:(60, 11) error: method readTypedList in class Parcel cannot be applied to given types; required: List<T>,Creator<T> found: ArrayList<CAP#1>,Creator<CAP#2> reason: inferred type does not conform to equality constraint(s) inferred: CAP#2 equality constraints(s): CAP#2,CAP#1 where T is a type-variable: T extends Object declared in method <T>readTypedList(List<T>,Creator<T>) where CAP#1,CAP#2 are fresh type-variables: CAP#1 extends BaseNewsItem from capture of ? extends BaseNewsItem CAP#2 extends BaseNewsItem from capture of ? extends BaseNewsItem
I'm a novice at Generics, so when I searched for the above error, I didn't completely get the solutions posted. I only added as I needed to convert ArrayList<MovieNewsItem> to ArrayList<BaseNewsItem>.
Relevant code from MovieNewsItem class:
public static final Creator<? extends BaseNewsItem> CREATOR = new Creator<MovieNewsItem>() {
public MovieNewsItem createFromParcel(Parcel source) {
return new MovieNewsItem(source);
}
public MovieNewsItem[] newArray(int size) {
return new MovieNewsItem[size];
}
};
Let me know if any further code snippets are needed.
UPDATE 1: (readTypedList from Android framework.)
public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
int M = list.size();
int N = readInt();
int i = 0;
for (; i < M && i < N; i++) {
if (readInt() != 0) {
list.set(i, c.createFromParcel(this));
} else {
list.set(i, null);
}
}
for (; i<N; i++) {
if (readInt() != 0) {
list.add(c.createFromParcel(this));
} else {
list.add(null);
}
}
for (; i<M; i++) {
list.remove(N);
}
}
MovieNewsListingFeed.java (Problem file):
public class MovieNewsListingFeed implements Parcelable {
PageDetail pg;
public void setItems(ArrayList<? extends BaseNewsItem> items) {
this.items = items;
}
ArrayList<? extends BaseNewsItem> items;
public ArrayList<? extends BaseNewsItem> getItemsTemp() {
return itemsTemp;
}
public void setItemsTemp(ArrayList<? extends BaseNewsItem> itemsTemp) {
this.itemsTemp = itemsTemp;
}
ArrayList<? extends BaseNewsItem> itemsTemp;
public ArrayList<? extends BaseNewsItem> getItems() {
return items;
}
public PageDetail getPg() {
return pg;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.pg, flags);
dest.writeTypedList(items);
}
public MovieNewsListingFeed() {
}
protected MovieNewsListingFeed(Parcel in) {
this.pg = in.readParcelable(PageDetail.class.getClassLoader());
this.items = new ArrayList<>();
in.readTypedList(items, MovieNewsItem.CREATOR);
}
public static final Parcelable.Creator<MovieNewsListingFeed> CREATOR = new Parcelable.Creator<MovieNewsListingFeed>() {
public MovieNewsListingFeed createFromParcel(Parcel source) {
return new MovieNewsListingFeed(source);
}
public MovieNewsListingFeed[] newArray(int size) {
return new MovieNewsListingFeed[size];
}
};
}
MovieNewsItem.java:
public class MovieNewsItem extends BaseNewsItem implements Parcelable {
String hl;
String imageid;
String syn;
String id;
String dm;
String tn;
String dl = "";
String sectionHeader;
String upd;
String ud;
private int validListPosition = -1;
public int getValidListPosition() {
return validListPosition;
}
#Override
public void setTitle(String title) {
}
#Override
public void setId(String id) {
}
#Override
public void setDate(String date) {
}
#Override
public void setNewsType(int newsType) {
}
public String getFormatedDate() {
return formatedDate;
}
String formatedDate;
int position;
int newSectionType = NewsType.CONTENT_TYPE_NEWS;
String dayHeading;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public void setNewSectionType(int newSectionType) {
this.newSectionType = newSectionType;
}
public String getDayHeading() {
return dayHeading;
}
public void setDayHeading(String dayHeading) {
this.dayHeading = dayHeading;
}
#Override
public void setValidListPosition(int listPosition) {
}
public String getWu() {
return wu;
}
String wu;
public String getHl() {
return hl;
}
public String getImageid() {
return imageid;
}
public String getSyn() {
return syn;
}
public String getId() {
return id;
}
public String getDm() {
return dm;
}
public String getTn() {
return tn;
}
public String getDl() {
return dl;
}
public String getSectionHeader() {
return sectionHeader;
}
public MovieNewsItem() {
}
#Override
public String getTitle() {
return (!TextUtils.isEmpty(getSyn())) ? getSyn() : getHl();
}
#Override
public String getDate() {
return getFormatedDate();
}
#Override
public int getNewsType() {
return newSectionType;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.hl);
dest.writeString(this.imageid);
dest.writeString(this.syn);
dest.writeString(this.id);
dest.writeString(this.dm);
dest.writeString(this.tn);
dest.writeString(this.dl);
dest.writeString(this.sectionHeader);
dest.writeString(this.upd);
dest.writeString(this.ud);
dest.writeInt(this.position);
dest.writeInt(this.newSectionType);
dest.writeString(this.dayHeading);
dest.writeString(this.wu);
}
protected MovieNewsItem(Parcel in) {
this.hl = in.readString();
this.imageid = in.readString();
this.syn = in.readString();
this.id = in.readString();
this.dm = in.readString();
this.tn = in.readString();
this.dl = in.readString();
this.sectionHeader = in.readString();
this.upd = in.readString();
this.ud = in.readString();
this.position = in.readInt();
this.newSectionType = in.readInt();
this.dayHeading = in.readString();
this.wu = in.readString();
}
public static final Creator<? extends BaseNewsItem> CREATOR = new Creator<MovieNewsItem>() {
public MovieNewsItem createFromParcel(Parcel source) {
return new MovieNewsItem(source);
}
public MovieNewsItem[] newArray(int size) {
return new MovieNewsItem[size];
}
};
#Override
public boolean equals(Object obj) {
MovieNewsItem newsItem = this;
if (obj instanceof MovieNewsItem) {
MovieNewsItem oldNewsItem = (MovieNewsItem) obj;
if (oldNewsItem != null &&
newsItem.id.equals(oldNewsItem.id)) {
return true;
}
}
return false;
}
}
BaseNewsItem.java:
public abstract class BaseNewsItem implements NewsItemType {
}
NewsItemType.java:
public interface NewsItemType extends Parcelable {
String getTitle();
String getId();
String getDate();
int getNewsType();
String getDayHeading();
int getValidListPosition();
int getPosition();
void setTitle(String title);
void setId(String id);
void setDate(String date);
void setNewsType(int newsType);
void setDayHeading(String dayHeading);
void setValidListPosition(int listPosition);
void setPosition(int position);
}
Your issue can be reproduced with this minimal example (replace ? extends Object by ? extends BaseNewsItem and the second list by a Parcelable.Creator and you'll see that the logic is exactly the same):
public void test() {
List<? extends Object> a1 = new ArrayList<> ();
List<? extends Object> a2 = new ArrayList<> ();
m(a1, a2); //your compilation error here
}
public <T> void m(List<T> a1, List<T> a2) { }
The problem is that the generic type of the two lists are unrelated: they both extend the same base class but that's all we know about them - for example a1 may be a List<String> and a2 a List<Integer>.
However the m method expects the two generic types to be the same - which is not what you are passing.
So you need to pass lists which have the same generic type, for example:
public void test() {
List<SomeBaseClass> a1 = new ArrayList<> ();
List<SomeBaseClass> a2 = new ArrayList<> ();
m(a1, a2); //compiles fine
}
public <T> void m(List<T> a1, List<T> a2) { }
This is due to type mis-match
Change
ArrayList<? extends BaseNewsItem> itemsTemp;
to
List<? extends BaseNewsItem> itemsTemp;
Change the method like this:
public final <T> void readTypedList(List<? extends BaseNewsItem> list, Parcelable.Creator<? extends BaseNewsItem> c) {
}
Hope it will work.

How to do the GET method from a hashmap with objects?

Im trying to get the id of a posto from an hashmap to compare the value in another class:
My class Posto:
public class Posto {
private int id;
private Point posicao;
private int capacidade;
private int quantidadeAtual;
private int gastoMedio;
public Posto(int id, Point posicao, int capacidade, int quantidadeAtual, int gastoMedio) {
this.id = id;
this.posicao = posicao;
this.capacidade = capacidade;
this.quantidadeAtual = quantidadeAtual;
this.gastoMedio = gastoMedio;
}
public int getPostoId() {
return id;
}
public void setPostoId(int id) {
this.id = id;
}
public Point getPostoPosicao() {
return posicao;
}
public void setPostoPosicao(Point posicao) {
this.posicao = posicao;
}
public int getPostoCapacidade() {
return capacidade;
}
public void setPostoCapacidade(int capacidade) {
this.capacidade = capacidade;
}
public int getPostoQuantidadeAtual() {
return quantidadeAtual;
}
public void setPostoQuantidadeAtual(int quantidadeAtual) {
this.quantidadeAtual = quantidadeAtual;
}
public int getPostoGastoMedio() {
return gastoMedio;
}
public void setPostoGastoMedio(int gastoMedio) {
this.gastoMedio = gastoMedio;
}
My MAIN class where i fill the hashmaps like this:
public class Main {
public static void main(String[] args) {
Central c = new Central( new Point(20, 300) );
setupCentral( c );
MenuCentral mc = new MenuCentral( c );
mc.menuPrincipal();
}
private static void setupCentral(Central c) {
//Posto p1 = new Posto(1,new Point(2,3),24,40,30);
c.addPosto(new Posto(1,new Point(10,10),10,200,180));
c.addPosto(new Posto(2,new Point(700,15),15,300,200));
}
}
And now my CENTRAL class where i have the method "addPosto" to fill the hashmap and i need the method "getPosto" to get the ids to compare in other class but i can't do it, i'm a little bit confused about the hashmaps.
public class Central {
private Point posicao;
private Map<Integer, Object> camioes = new HashMap<Integer,Object>( );
private Map<Integer,Object> postos = new HashMap<Integer,Object>( );
public Central(Point posicao) {
this.posicao = posicao;
}
public Point getPosicao() {
return posicao;
}
public void setPosicao(Point posicao) {
this.posicao = posicao;
}
public void addPosto( Posto p ){
postos.put(p.getPostoId(), p);
}
***public int getPosto (int id){
}***
}
Your Map has only one value type.
private final Map<Integer, Posto> postos = new HashMap<>();
And you only add this type.
public void addPosto( Posto p ){
postos.put(p.getPostoId(), p);
}
so it makes sense to expect this type.
public Posto getPosto(int id) {
return postos.get(id);
}
If you want to leave the Map as it is (which is a bad idea IMHO you can use an explicit cast)
public Posto getPosto(int id) {
return (Posto) postos.get(id);
}
This is needlessly verbose and error prone. At some point doing this will almost certainly lead to a bug which never needed to happen.
public Posto getPosto (int id)
{
return postos.get(id);
}
sice you are adding posto class to the hashmap use generics
private Map<Integer, Posto> camioes = new HashMap<Integer,Posto>( );
private Map<Integer,Posto> postos = new HashMap<Integer,Posto>( );
you can iterate the hashmap and get all the values
for (Integer key : camioes.keySet()) {
Posto p = postos.get(key);
System.out.println(p.getPostoId());
}
}

Proxying objects in a deep object graph (Java)

public class ObjectToProxy
{
List<ObjectToProxy> potentiallyCircularReference;
}
public class SubClass
{
private ObjectToProxy aField;
Set<ObjectToProxy> aSetOfObjectsToProxy;
}
public class CrazyObject
{
Map<Integer, ObjectToProxy> proxiedObjects;
List<SubClass> manySubClasses;
}
public class ComplexObject
{
List<CrazyObject> crazyObjects;
private final ObjectToProxy storedAsAField;
}
I have a complex object graph. Lets say it looks a little like the one above (even though it is much deeper in the real system). I would like, after being given ComplexObject, to be able to traverse the object graph and replace all ObjectToProxys with a proxying object.
Is this doable?
The reason for this is that we have some pretty big nasty objects which we partially load on the servers side (legacy, you're my friend!). We have a semi-working solution that uses proxying on the client side to go through and loads the full object when needed.
edit I would like to replace every instance of ObjectProxy connected to a ComplexObject.
public static class ProxyObject extends ObjectToProxy
{
private final ObjectToProxy objectToProxy;
public ProxyObject(ObjectToProxy objectToProxy)
{
this.objectToProxy = objectToProxy;
}
#Override
public String toString()
{
return "ProxyObject";
}
}
public static class ObjectToProxy
{
List<ObjectToProxy> potentiallyCircularReference;
public ObjectToProxy()
{
potentiallyCircularReference = new ArrayList<>();
potentiallyCircularReference.add(this);
}
#Override
public String toString()
{
return "ObjectToProxy";
}
}
public static class SubClass
{
ObjectToProxy aField;
Set<ObjectToProxy> aSetOfObjectsToProxy;
}
public static class CrazyObject
{
Map<Integer, ObjectToProxy> proxiedObjects;
List<SubClass> manySubClasses;
public CrazyObject()
{
proxiedObjects = new HashMap<>();
proxiedObjects.put(1, new ObjectToProxy());
}
}
public static class ComplexObject
{
List<CrazyObject> crazyObjects;
final ObjectToProxy storedAsAField;
public ComplexObject()
{
this.storedAsAField = new ObjectToProxy();
crazyObjects = new ArrayList<>();
crazyObjects.add(new CrazyObject());
}
#Override
public String toString()
{
return "myField: " + storedAsAField.toString();
}
}
public static void main(String[] args) throws Exception
{
ComplexObject obj = new ComplexObject();
Set<Object> visitedObjects = Sets.newIdentityHashSet();
Queue<Object> objectsToVisit = new LinkedList<>();
visitedObjects.add(obj);
objectsToVisit.add(obj);
while (!objectsToVisit.isEmpty())
{
handleFields(objectsToVisit.poll(), visitedObjects, objectsToVisit);
}
System.out.println(obj.toString());
}
private static void handleFields(Object obj, Set<Object> visitedObjects, Queue<Object> objectsToVisit) throws Exception
{
List<Field> fields = getAllFields(obj);
for (Field field : fields)
{
field.setAccessible(true);
Object fieldValue = field.get(obj);
if (fieldValue != null && !visitedObjects.contains(fieldValue))
{
if (fieldValue instanceof Object[])
{
visitedObjects.add(fieldValue);
Object[] array = (Object[])fieldValue;
for (Object arrayObj : array)
{
if (arrayObj != null && !objectsToVisit.contains(arrayObj))
{
visitedObjects.add(arrayObj);
if (!DontLookAt.contains(arrayObj.getClass()))
objectsToVisit.add(arrayObj);
}
}
}
else
{
if (!DontLookAt.contains(fieldValue.getClass()))
objectsToVisit.add(fieldValue);
}
if (fieldValue.getClass().equals(ObjectToProxy.class))
{
field.set(obj, new ProxyObject((ObjectToProxy)fieldValue));
}
else if (fieldValue instanceof ObjectToProxy[])
{
ObjectToProxy[] array = (ObjectToProxy[])fieldValue;
for (int i = 0; i < array.length; i++)
{
if (array[i] != null)
array[i] = new ProxyObject(array[i]);
}
}
}
}
}
private static final Set<Class> DontLookAt = getDontLookAtSet();
private static Set<Class> getDontLookAtSet()
{
Set<Class> set = new HashSet<>();
set.add(Long.class);
set.add(Boolean.class);
set.add(Integer.class);
set.add(String.class);
set.add(Byte.class);
set.add(Double.class);
set.add(Float.class);
set.add(Class.class);
return set;
}
private static List<Field> getAllFields(Object obj) throws Exception
{
List<Field> output = new ArrayList<>();
Class klazz = obj.getClass();
while (!klazz.equals(Object.class))
{
Field[] fields = klazz.getDeclaredFields();
output.addAll(Arrays.asList(fields));
klazz = klazz.getSuperclass();
}
return output;
}
For anyone wondering, The above simulates and does what I'm after. I'm sure it isn't perfect, but it is good enough for my purposes.

Java implementing comparator on ArrayList

I'm quite new to Java so this is probably pretty straight forward question.
I want to sort an ArrayList in the class MediaLib based on the natural order of a specified key.
I can't work out how to use my comparator (compareTo(MediaInterface, key)) which is in the Media class. Whats the best way to go about this?
package assign1;
import java.util.*;
public class Media implements MediaInterface {
private Map<String, Object> fields;
private static int compare;
public Media(String title, String format) {
fields = new TreeMap<String, Object>();
fields.put("title", title);
fields.put("format", format);
}
public Object get(String key) {
return fields.get(key);
}
public void put(String key, Object value) {
fields.put(key, value);
}
public boolean hasKeywords(String[] words, boolean combineWithAND) {
Collection<Object> values = (Collection<Object>) fields.values();
int count = 0;
int size = 0;
for (String s: words) {
for (Object o: values) {
String t = o.toString();
if (t.indexOf(s) >= 0) {
count++;
break;
}
}
size++;
}
if ((count == 0 && !combineWithAND) || (combineWithAND && (count != size))) {
return false;
}
return true;
}
public int compareTo(MediaInterface mi, String key) { //<<<<<<<------calling this!!
if (mi == null)
throw new NullPointerException();
Media m = (Media) mi;
Comparable mValue = (Comparable) m.get(key);
Comparable lValue = (Comparable) fields.get(key);
if ((mValue == null) && (lValue == null)){
return 0;
}
if ((lValue == null)){
return 1;
}
if ((mValue == null)){
return -1;
}
return (lValue).compareTo(mValue);
}
#Override
public int compareTo(MediaInterface mi) {
if (mi == null)
throw new NullPointerException();
Media m = (Media) mi;
Set<String> lSet = fields.keySet();
if (compareTo(m, "title") != 0) {
return compareTo(m, "title");
}
if (compareTo(m, "year") != 0) {
return compareTo(m, "year");
}
for (String s: lSet) {
if (compareTo(m, s) != 0) {
return compareTo(m, s);
}
}
return 0;
}
public boolean equals(Object object) {
if (object == null)
return false;
if (!(object instanceof Media))
return false;
Media m = (Media) object;
if (compareTo(m) != 0) {
return false;
}
return true;
}
}
package assign1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
public class MediaLib implements Searchable {
private ArrayList<MediaInterface> media;
public MediaLib() {
media = new ArrayList<MediaInterface>();
}
#Override
public void add(MediaInterface mi) {
if (media.isEmpty()) {
media.add(mi);
}
else {
for (MediaInterface m: media) {
if (mi.equals(m)) {
return;
}
}
media.add(mi);
}
}
#Override
public boolean contains(MediaInterface mi) {
for (MediaInterface m: media) {
if (mi.equals(m)) {
return true;
}
}
return false;
}
#Override
public Collection<MediaInterface> findByKeyword(String[] words, boolean combineWithAND) {
Collection<MediaInterface> foundList = new ArrayList<MediaInterface>();
for (MediaInterface mi: media) {
if (mi.hasKeywords(words, combineWithAND)) {
foundList.add(mi);
}
}
return foundList;
}
#Override
public Collection<MediaInterface> findByTitle(String str) {
Collection<MediaInterface> foundList = new ArrayList<MediaInterface>();
for (MediaInterface mi: media) {
if ((mi.get("title")).equals(str)) {
foundList.add(mi);
}
}
return foundList;
}
#Override
public Collection<MediaInterface> getAllWithFormat(String formatName) {
Collection<MediaInterface> foundList = new ArrayList<MediaInterface>();
for (MediaInterface mi: media) {
if ((mi.get("format")).equals(formatName)) {
foundList.add(mi);
}
}
return foundList;
}
public Collection<MediaInterface> getAll() {
Collection<MediaInterface> fullList = new ArrayList<MediaInterface>();
for (MediaInterface mi: media) {
fullList.add(mi);
}
return fullList;
}
#Override
public void removeAllWithKeyword(String[] words, boolean combineWithAND) {
Collection<MediaInterface> foundList = findByKeyword(words, combineWithAND);
for (MediaInterface mi: foundList) {
media.remove(mi);
}
}
#Override
public void removeAllWithFormat(String format) {
Collection<MediaInterface> foundList = getAllWithFormat(format);
for (MediaInterface mi: foundList) {
media.remove(mi);
}
}
#Override
public void sort() {
Collections.sort(media);
}
#Override
public void sort(final String fieldName) {
Collections.sort(media, new Media.compareTo(MediaInterface, fieldName)) //<<<<<--------Trying to call compareTo()
}
}
public void parse(java.io.BufferedReader br) throws java.io.IOException {
while(br.readLine()!= null) {
Media mi = new Media(/n br.readLine(), br.readLine());
while
}
}
}
You already implement the Comparable interface in your MediaInterface class, this is a generic interface, so you then implement Comparable<MediaInterface> which will then require you to implement a method with the signature
public int compareTo(final MediaInterface other)
This is why your call to Collections.sort(media); compiles
In order to sort by a specific field name, you need to provide an instance of a Comparator, the easiest way to do this will be to create an inner class in your Media class which you can then pass into Collections.sort. For example
public class Media implements MediaInterface {
public static final class FieldComparator implements Comparator<Media> {
private final String field;
public FieldComparator(final String field) {
this.field = field;
}
public int compare(final Media a, final Media b) {
// implementation to compare a.field to b.field
}
}
}
You can then rewrite your second sort method as
#Override
public void sort(final String fieldName) {
Collections.sort(media, new Media.FieldComparator(fieldName));
}

How to use Comparator in Java to sort

I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my code:
Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at New.TestPeople.main(TestPeople.java:18)
Here is my code:
import java.util.Comparator;
public class People implements Comparator {
private int id;
private String info;
private double price;
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
public int compare(Object obj1, Object obj2) {
Integer p1 = ((People) obj1).getid();
Integer p2 = ((People) obj2).getid();
if (p1 > p2) {
return 1;
} else if (p1 < p2){
return -1;
} else {
return 0;
}
}
}
import java.util.ArrayList;
import java.util.Collections;
public class TestPeople {
public static void main(String[] args) {
ArrayList peps = new ArrayList();
peps.add(new People(123, "M", 14.25));
peps.add(new People(234, "M", 6.21));
peps.add(new People(362, "F", 9.23));
peps.add(new People(111, "M", 65.99));
peps.add(new People(535, "F", 9.23));
Collections.sort(peps);
for (int i = 0; i < peps.size(); i++){
System.out.println(peps.get(i));
}
}
}
I believe it has to do something with the casting in the compare method but I was playing around with it and still could not find the solution
There are a couple of awkward things with your example class:
it's called People while it has a price and info (more something for objects, not people);
when naming a class as a plural of something, it suggests it is an abstraction of more than one thing.
Anyway, here's a demo of how to use a Comparator<T>:
public class ComparatorDemo {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Joe", 24),
new Person("Pete", 18),
new Person("Chris", 21)
);
Collections.sort(people, new LexicographicComparator());
System.out.println(people);
Collections.sort(people, new AgeComparator());
System.out.println(people);
}
}
class LexicographicComparator implements Comparator<Person> {
#Override
public int compare(Person a, Person b) {
return a.name.compareToIgnoreCase(b.name);
}
}
class AgeComparator implements Comparator<Person> {
#Override
public int compare(Person a, Person b) {
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
#Override
public String toString() {
return String.format("{name=%s, age=%d}", name, age);
}
}
EDIT
And an equivalent Java 8 demo would look like this:
public class ComparatorDemo {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Joe", 24),
new Person("Pete", 18),
new Person("Chris", 21)
);
Collections.sort(people, (a, b) -> a.name.compareToIgnoreCase(b.name));
System.out.println(people);
Collections.sort(people, (a, b) -> a.age < b.age ? -1 : a.age == b.age ? 0 : 1);
System.out.println(people);
}
}
Here's a super short template to do the sorting right away :
Collections.sort(people, new Comparator<Person>() {
#Override
public int compare(final Person lhs, Person rhs) {
// TODO return 1 if rhs should be before lhs
// return -1 if lhs should be before rhs
// return 0 otherwise (meaning the order stays the same)
}
});
If it's hard to remember, try to just remember that it's similar (in terms of the sign of the number) to:
lhs-rhs
That's in case you want to sort in ascending order : from smallest number to largest number.
Use People implements Comparable<People> instead; this defines the natural ordering for People.
A Comparator<People> can also be defined in addition, but People implements Comparator<People> is not the right way of doing things.
The two overloads for Collections.sort are different:
<T extends Comparable<? super T>> void sort(List<T> list)
Sorts Comparable objects using their natural ordering
<T> void sort(List<T> list, Comparator<? super T> c)
Sorts whatever using a compatible Comparator
You're confusing the two by trying to sort a Comparator (which is again why it doesn't make sense that Person implements Comparator<Person>). Again, to use Collections.sort, you need one of these to be true:
The type must be Comparable (use the 1-arg sort)
A Comparator for the type must be provided (use the 2-args sort)
Related questions
When to use Comparable vs Comparator
Sorting an ArrayList of Contacts
Also, do not use raw types in new code. Raw types are unsafe, and it's provided only for compatibility.
That is, instead of this:
ArrayList peps = new ArrayList(); // BAD!!! No generic safety!
you should've used the typesafe generic declaration like this:
List<People> peps = new ArrayList<People>(); // GOOD!!!
You will then find that your code doesn't even compile!! That would be a good thing, because there IS something wrong with the code (Person does not implements Comparable<Person>), but because you used raw type, the compiler didn't check for this, and instead you get a ClassCastException at run-time!!!
This should convince you to always use typesafe generic types in new code. Always.
See also
What is a raw type and why shouldn't we use it?
For the sake of completeness, here's a simple one-liner compare method:
Collections.sort(people, new Comparator<Person>() {
#Override
public int compare(Person lhs, Person rhs) {
return Integer.signum(lhs.getId() - rhs.getId());
}
});
Java 8 added a new way of making Comparators that reduces the amount of code you have to write, Comparator.comparing. Also check out Comparator.reversed
Here's a sample
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class ComparatorTest {
#Test
public void test() {
List<Person> peopleList = new ArrayList<>();
peopleList.add(new Person("A", 1000));
peopleList.add(new Person("B", 1));
peopleList.add(new Person("C", 50));
peopleList.add(new Person("Z", 500));
//sort by name, ascending
peopleList.sort(Comparator.comparing(Person::getName));
assertTrue(peopleList.get(0).getName().equals("A"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
//sort by name, descending
peopleList.sort(Comparator.comparing(Person::getName).reversed());
assertTrue(peopleList.get(0).getName().equals("Z"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
//sort by age, ascending
peopleList.sort(Comparator.comparing(Person::getAge));
assertTrue(peopleList.get(0).getAge() == 1);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
//sort by age, descending
peopleList.sort(Comparator.comparing(Person::getAge).reversed());
assertTrue(peopleList.get(0).getAge() == 1000);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
}
For the sake of completeness.
Using Java8
people.sort(Comparator.comparingInt(People::getId));
if you want in descending order
people.sort(Comparator.comparingInt(People::getId).reversed());
You want to implement Comparable, not Comparator. You need to implement the compareTo method. You're close though. Comparator is a "3rd party" comparison routine. Comparable is that this object can be compared with another.
public int compareTo(Object obj1) {
People that = (People)obj1;
Integer p1 = this.getId();
Integer p2 = that.getid();
if (p1 > p2 ){
return 1;
}
else if (p1 < p2){
return -1;
}
else
return 0;
}
Note, you may want to check for nulls in here for getId..just in case.
Two corrections:
You have to make an ArrayList of People objects:
ArrayList<People> preps = new ArrayList<People>();
After adding the objects to the preps, use:
Collections.sort(preps, new CompareId());
Also, add a CompareId class as:
class CompareId implements Comparator {
public int compare(Object obj1, Object obj2) {
People t1 = (People)obj1;
People t2 = (People)obj2;
if (t1.marks > t2.marks)
return 1;
else
return -1;
}
}
Here's an example of a Comparator that will work for any zero arg method that returns a Comparable. Does something like this exist in a jdk or library?
import java.lang.reflect.Method;
import java.util.Comparator;
public class NamedMethodComparator implements Comparator<Object> {
//
// instance variables
//
private String methodName;
private boolean isAsc;
//
// constructor
//
public NamedMethodComparator(String methodName, boolean isAsc) {
this.methodName = methodName;
this.isAsc = isAsc;
}
/**
* Method to compare two objects using the method named in the constructor.
*/
#Override
public int compare(Object obj1, Object obj2) {
Comparable comp1 = getValue(obj1, methodName);
Comparable comp2 = getValue(obj2, methodName);
if (isAsc) {
return comp1.compareTo(comp2);
} else {
return comp2.compareTo(comp1);
}
}
//
// implementation
//
private Comparable getValue(Object obj, String methodName) {
Method method = getMethod(obj, methodName);
Comparable comp = getValue(obj, method);
return comp;
}
private Method getMethod(Object obj, String methodName) {
try {
Class[] signature = {};
Method method = obj.getClass().getMethod(methodName, signature);
return method;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
private Comparable getValue(Object obj, Method method) {
Object[] args = {};
try {
Object rtn = method.invoke(obj, args);
Comparable comp = (Comparable) rtn;
return comp;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
public static Comparator<JobSet> JobEndTimeComparator = new Comparator<JobSet>() {
public int compare(JobSet j1, JobSet j2) {
int cost1 = j1.cost;
int cost2 = j2.cost;
return cost1-cost2;
}
};
The solution can be optimized in following way:
Firstly, use a private inner class as the scope for the fields is to be the enclosing class TestPeople so as the implementation of class People won't get exposed to outer world. This can be understood in terms of creating an APIthat expects a sorted list of people
Secondly, using the Lamba expression(java 8) which reduces the code, hence development effort
Hence code would be as below:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TestPeople {
public static void main(String[] args) {
ArrayList<People> peps = new ArrayList<>();// Be specific, to avoid
// classCast Exception
TestPeople test = new TestPeople();
peps.add(test.new People(123, "M", 14.25));
peps.add(test.new People(234, "M", 6.21));
peps.add(test.new People(362, "F", 9.23));
peps.add(test.new People(111, "M", 65.99));
peps.add(test.new People(535, "F", 9.23));
/*
* Collections.sort(peps);
*
* for (int i = 0; i < peps.size(); i++){
* System.out.println(peps.get(i)); }
*/
// The above code can be replaced by followin:
peps.sort((People p1, People p2) -> p1.getid() - p2.getid());
peps.forEach((p) -> System.out.println(" " + p.toString()));
}
private class People {
private int id;
#Override
public String toString() {
return "People [id=" + id + ", info=" + info + ", price=" + price + "]";
}
private String info;
private double price;
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
}
}
Here is a lambda version of comparator. This will sort a string list according to length.
Collections.sort(str, (str1, str2) -> {
if(str1.length() < str2.length())
return 1;
else if(str2.length() < str1.length())
return -1;
else
return 0;
});
You should use the overloaded sort(peps, new People()) method
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<People> peps = new ArrayList<>();
peps.add(new People(123, "M", 14.25));
peps.add(new People(234, "M", 6.21));
peps.add(new People(362, "F", 9.23));
peps.add(new People(111, "M", 65.99));
peps.add(new People(535, "F", 9.23));
Collections.sort(peps, new People().new ComparatorId());
for (int i = 0; i < peps.size(); i++)
{
System.out.println(peps.get(i));
}
}
}
class People
{
private int id;
private String info;
private double price;
public People()
{
}
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
class ComparatorId implements Comparator<People>
{
#Override
public int compare(People obj1, People obj2) {
Integer p1 = obj1.getid();
Integer p2 = obj2.getid();
if (p1 > p2) {
return 1;
} else if (p1 < p2){
return -1;
} else {
return 0;
}
}
}
}
Here is my answer for a simple comparator tool
public class Comparator {
public boolean isComparatorRunning = false;
public void compareTableColumns(List<String> tableNames) {
if(!isComparatorRunning) {
isComparatorRunning = true;
try {
for (String schTableName : tableNames) {
Map<String, String> schemaTableMap = ComparatorUtil.getSchemaTableMap(schTableName);
Map<String, ColumnInfo> primaryColMap = ComparatorUtil.getColumnMetadataMap(DbConnectionRepository.getConnectionOne(), schemaTableMap);
Map<String, ColumnInfo> secondaryColMap = ComparatorUtil.getColumnMetadataMap(DbConnectionRepository.getConnectionTwo(), schemaTableMap);
ComparatorUtil.publishColumnInfoOutput("Comparing table : "+ schemaTableMap.get(CompConstants.TABLE_NAME));
compareColumns(primaryColMap, secondaryColMap);
}
} catch (Exception e) {
ComparatorUtil.publishColumnInfoOutput("ERROR"+e.getMessage());
}
isComparatorRunning = false;
}
}
public void compareColumns(Map<String, ColumnInfo> primaryColMap, Map<String, ColumnInfo> secondaryColMap) {
try {
boolean isEqual = true;
for(Map.Entry<String, ColumnInfo> entry : primaryColMap.entrySet()) {
String columnName = entry.getKey();
ColumnInfo primaryColInfo = entry.getValue();
ColumnInfo secondaryColInfo = secondaryColMap.remove(columnName);
if(secondaryColInfo == null) {
// column is not present in Secondary Environment
ComparatorUtil.publishColumnInfoOutput("ALTER", primaryColInfo);
isEqual = false;
continue;
}
if(!primaryColInfo.equals(secondaryColInfo)) {
isEqual = false;
// Column not equal in secondary env
ComparatorUtil.publishColumnInfoOutput("MODIFY", primaryColInfo);
}
}
if(!secondaryColMap.isEmpty()) {
isEqual = false;
for(Map.Entry<String, ColumnInfo> entry : secondaryColMap.entrySet()) {
// column is not present in Primary Environment
ComparatorUtil.publishColumnInfoOutput("DROP", entry.getValue());
}
}
if(isEqual) {
ComparatorUtil.publishColumnInfoOutput("--Exact Match");
}
} catch (Exception e) {
ComparatorUtil.publishColumnInfoOutput("ERROR"+e.getMessage());
}
}
public void compareTableColumnsValues(String primaryTableName, String primaryColumnNames, String primaryCondition, String primaryKeyColumn,
String secTableName, String secColumnNames, String secCondition, String secKeyColumn) {
if(!isComparatorRunning) {
isComparatorRunning = true;
Connection conn1 = DbConnectionRepository.getConnectionOne();
Connection conn2 = DbConnectionRepository.getConnectionTwo();
String query1 = buildQuery(primaryTableName, primaryColumnNames, primaryCondition, primaryKeyColumn);
String query2 = buildQuery(secTableName, secColumnNames, secCondition, secKeyColumn);
try {
Map<String,Map<String, Object>> query1Data = executeAndRefactorData(conn1, query1, primaryKeyColumn);
Map<String,Map<String, Object>> query2Data = executeAndRefactorData(conn2, query2, secKeyColumn);
for(Map.Entry<String,Map<String, Object>> entry : query1Data.entrySet()) {
String key = entry.getKey();
Map<String, Object> value = entry.getValue();
Map<String, Object> secondaryValue = query2Data.remove(key);
if(secondaryValue == null) {
ComparatorUtil.publishColumnValuesInfoOutput("NO SUCH VALUE AVAILABLE IN SECONDARY DB "+ value.toString());
continue;
}
compareMap(value, secondaryValue, key);
}
if(!query2Data.isEmpty()) {
ComparatorUtil.publishColumnValuesInfoOutput("Extra Values in Secondary table "+ ((Map)query2Data.values()).values().toString());
}
} catch (Exception e) {
ComparatorUtil.publishColumnValuesInfoOutput("ERROR"+e.getMessage());
}
isComparatorRunning = false;
}
}
private void compareMap(Map<String, Object> primaryValues, Map<String, Object> secondaryValues, String columnIdentification) {
for(Map.Entry<String, Object> entry : primaryValues.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Object secValue = secondaryValues.get(key);
if(value!=null && secValue!=null && !String.valueOf(value).equalsIgnoreCase(String.valueOf(secValue))) {
ComparatorUtil.publishColumnValuesInfoOutput(columnIdentification+" : Secondary Table does not match value ("+ value +") for column ("+ key+")");
}
if(value==null && secValue!=null) {
ComparatorUtil.publishColumnValuesInfoOutput(columnIdentification+" : Values not available in primary table for column "+ key);
}
if(value!=null && secValue==null) {
ComparatorUtil.publishColumnValuesInfoOutput(columnIdentification+" : Values not available in Secondary table for column "+ key);
}
}
}
private String buildQuery(String tableName, String column, String condition, String keyCol) {
if(!"*".equalsIgnoreCase(column)) {
String[] keyColArr = keyCol.split(",");
for(String key: keyColArr) {
if(!column.contains(key.trim())) {
column+=","+key.trim();
}
}
}
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("select "+column+" from "+ tableName);
if(!ComparatorUtil.isNullorEmpty(condition)) {
queryBuilder.append(" where 1=1 and "+condition);
}
return queryBuilder.toString();
}
private Map<String,Map<String, Object>> executeAndRefactorData(Connection connection, String query, String keyColumn) {
Map<String,Map<String, Object>> result = new HashMap<String, Map<String,Object>>();
try {
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.setFetchSize(1000);
if (resultSet != null && !resultSet.isClosed()) {
while (resultSet.next()) {
Map<String, Object> columnValueDetails = new HashMap<String, Object>();
int columnCount = resultSet.getMetaData().getColumnCount();
for (int i=1; i<=columnCount; i++) {
String columnName = String.valueOf(resultSet.getMetaData().getColumnName(i));
Object columnValue = resultSet.getObject(columnName);
columnValueDetails.put(columnName, columnValue);
}
String[] keys = keyColumn.split(",");
String newKey = "";
for(int j=0; j<keys.length; j++) {
newKey += String.valueOf(columnValueDetails.get(keys[j]));
}
result.put(newKey , columnValueDetails);
}
}
} catch (SQLException e) {
ComparatorUtil.publishColumnValuesInfoOutput("ERROR"+e.getMessage());
}
return result;
}
}
Utility Tool for the same
public class ComparatorUtil {
public static Map<String, String> getSchemaTableMap(String tableNameWithSchema) {
if(isNullorEmpty(tableNameWithSchema)) {
return null;
}
Map<String, String> result = new LinkedHashMap<>();
int index = tableNameWithSchema.indexOf(".");
String schemaName = tableNameWithSchema.substring(0, index);
String tableName = tableNameWithSchema.substring(index+1);
result.put(CompConstants.SCHEMA_NAME, schemaName);
result.put(CompConstants.TABLE_NAME, tableName);
return result;
}
public static Map<String, ColumnInfo> getColumnMetadataMap(Connection conn, Map<String, String> schemaTableMap) {
try {
String schemaName = schemaTableMap.get(CompConstants.SCHEMA_NAME);
String tableName = schemaTableMap.get(CompConstants.TABLE_NAME);
ResultSet resultSetConnOne = conn.getMetaData().getColumns(null, schemaName, tableName, null);
Map<String, ColumnInfo> resultSetTwoColInfo = getColumnInfo(schemaName, tableName, resultSetConnOne);
return resultSetTwoColInfo;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* Number Type mapping
* 12-----VARCHAR
* 3-----DECIMAL
* 93-----TIMESTAMP
* 1111-----OTHER
*/
public static Map<String, ColumnInfo> getColumnInfo(String schemaName, String tableName, ResultSet columns) {
try {
Map<String, ColumnInfo> tableColumnInfo = new LinkedHashMap<String, ColumnInfo>();
while (columns.next()) {
ColumnInfo columnInfo = new ColumnInfo();
columnInfo.setSchemaName(schemaName);
columnInfo.setTableName(tableName);
columnInfo.setColumnName(columns.getString("COLUMN_NAME"));
columnInfo.setDatatype(columns.getString("DATA_TYPE"));
columnInfo.setColumnsize(columns.getString("COLUMN_SIZE"));
columnInfo.setDecimaldigits(columns.getString("DECIMAL_DIGITS"));
columnInfo.setIsNullable(columns.getString("IS_NULLABLE"));
tableColumnInfo.put(columnInfo.getColumnName(), columnInfo);
}
return tableColumnInfo;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean isNullOrEmpty(Object obj) {
if (obj == null)
return true;
if (String.valueOf(obj).equalsIgnoreCase("NULL"))
return true;
if (obj.toString().trim().length() == 0)
return true;
return false;
}
public static boolean isNullorEmpty(String str) {
if(str == null)
return true;
if(str.trim().length() == 0)
return true;
return false;
}
public static void publishColumnInfoOutput(String type, ColumnInfo columnInfo) {
String str = "ALTER TABLE "+columnInfo.getSchemaName()+"."+columnInfo.getTableName();
switch(type.toUpperCase()) {
case "ALTER":
if("NUMBER".equalsIgnoreCase(columnInfo.getDatatype()) || "DATE".equalsIgnoreCase(columnInfo.getDatatype())) {
str += " ADD ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype()+");";
} else {
str += " ADD ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype() +"("+columnInfo.getColumnsize()+"));";
}
break;
case "DROP":
str += " DROP ("+columnInfo.getColumnName()+");";
break;
case "MODIFY":
if("NUMBER".equalsIgnoreCase(columnInfo.getDatatype()) || "DATE".equalsIgnoreCase(columnInfo.getDatatype())) {
str += " MODIFY ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype()+");";
} else {
str += " MODIFY ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype() +"("+columnInfo.getColumnsize()+"));";
}
break;
}
publishColumnInfoOutput(str);
}
public static Map<Integer, String> allJdbcTypeName = null;
public static Map<Integer, String> getAllJdbcTypeNames() {
Map<Integer, String> result = new HashMap<Integer, String>();
if(allJdbcTypeName != null)
return allJdbcTypeName;
try {
for (Field field : java.sql.Types.class.getFields()) {
result.put((Integer) field.get(null), field.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
return allJdbcTypeName=result;
}
public static String getStringPlaces(String[] attribs) {
String params = "";
for(int i=0; i<attribs.length; i++) { params += "?,"; }
return params.substring(0, params.length()-1);
}
}
Column Info Class
public class ColumnInfo {
private String schemaName;
private String tableName;
private String columnName;
private String datatype;
private String columnsize;
private String decimaldigits;
private String isNullable;
If you are using Java 8 then it's better to use below code like this:
Comparator<People> comparator = Comparator.comparing(People::getName);
And then simply use:
Collections.sort(list, comparator);
If you are using Java 7 or below then you can use a comparator for customized sorting order by implementing compare method.
For example:
import java.util.Comparator;
public class PeopleNameComparator implements Comparator<People> {
#Override
public int compare(People people1, People people2) {
return people1.getName().compareTo(people2.getName());
}
}
And then simply use like this:
Collections.sort(list, new PeopleNameComparator);
Do not waste time implementing Sorting Algorithm by your own. Instead use Collections.sort() to sort data.

Categories

Resources