sort Object.String with Java - java

I have a Object:
public class ListAnnotationsOrigin implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8443084209405942551L;
#JsonProperty("opcombo")
private List<opcombo> listComboOp;
#JsonProperty("vicombo")
private List<vicombo> listComboVi;
#JsonProperty("vicombo")
private String vicombo;
#JsonProperty("viversion")
private String idVersionVi;
#JsonProperty("closed")
private String closed;
#JsonProperty("params")
private List<SegmentOrigin> listSegmentOrigin; // <-- here
// getters,setters etc.
I want sort listSegmentOrigin
#Entity
#Table(name = "SegmentOrigin")
public class SegmentOrigin implements Comparable<T>{ // <-- ERROR
....
#JsonProperty("idSegment")
private String idSegment;
public int compareTo(SegmentOrigin arg0) {
if (this.getIdSegment().compareTo(arg0.getIdSegment())) { // <<--ERROR type mismatch: cannot convert from int to boolean
return 1;
} else {
return 0;
}
}
}
In my controller->
ListAnnotationsOrigin list = this.getListAnnotationsOrigin ();
return Collections.sort((List<SegmentOrigin>) list.getListSegmentOrigin());
I send my List from ListAnnotationsOrigin in an orderly manner, Then when I implements Comparable{ I get red line "implements methods unics"
I import -> public int compareTo(SegmentOrigin arg0) { ... and I get other error, thanks.

Your entity should look like this :
#Entity
#Table(name = "SegmentOrigin")
public class SegmentOrigin implements Comparable<SegmentOrigin>{
#JsonProperty("idSegment")
private String idSegment;
public int compareTo(SegmentOrigin arg0) {
return this.getIdSegment().compareTo(arg0.getIdSegment()); // Check nullity if needed
}
}
implements Comparable<SegmentOrigin> means that your object can be compared with another SegmentOrigin object.

Related

Java Serializable and lambda expressions

I need to save an object on file, then retrieve it later. The object itself implements the interface Serializable, but one of its fields contains lambda expressions. Apparently this counts as a field that does not implements the Serializable interface and I get a java.io.NotSerializableException.
I do not want to drastically change my code, but I do not know what to do in such a situation. Someone has a suggestion?
Here is a sample code that replicates this problem:
public class SerObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2691834780794406081L;
public SerField field;
public SerObject(SerField field) {
this.field = field;
}
public String stringRepresentation() {
return this.field.name() + "\t" + field.lambda.apply(field);
}
static final String pathname = "D:\\JavaData\\file.obj";
public static void main(String[] args) {
SerObject obj = new SerObject(new SerField("Field", (field) -> "Class is " + field.getClass().getName() ));
SerializableUtilities.saveObject(new File(pathname), obj);
SerObject loadedObj = SerializableUtilities.loadObject(new File(pathname));
System.out.println(loadedObj.stringRepresentation());
}
}
public class SerField implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5058433150929459799L;
protected String name;
protected Function<SerField, String> lambda;
public SerField(String name, Function<SerField, String> lambda) {
this.name = name;
this.lambda = lambda;
}
public abstract String name() {
return this.name;
}
}

Easy access Object Getter with Java

Method 1: traditional getter/setter
Toyota class:
public class ToyotaCar implements Serializable {
private static final long serialVersionUID = 2011932556974180375L;
private int miles;
public void addMiles(int miles){
this.miles = miles;
}
public int getMiles(){
return miles;
}
}
Human class:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private ToyotaCar car;
public void setCar(ToyotaCar car){
this.car = car;
}
public int getCar(){
return car;
}
public void addCarMiles(int num){
getCar().addMiles(num);
}
}
Method 2: "other"
Toyota class: -same as above toyota class-
Additional containerHandler class:
public enum HumanContentsContainer {
CAR{
#Override public Object getContainer(){
return new ToyotaCar();
}
},
HOUSE;
public Object getContainer(){ //because cannot be static enum constant as every human has different items
return null;
}
}
Human class:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private HashMap<HumanContentsContainer, Object> contents;
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
contents.put(c, c.getContainer());
}
}
public HashMap<HumanContentsContainer, Object> getContents(){
return contents;
}
public void addCarMiles(int num){
//TODO how to replicate this: getCar().addMiles(num);???
}
//TODO i dont want to use the below method because whats the point of creating a whole container handler if im just going to use a traditional getter again?
//public ToyotaCar getCar(){
// return (ToyotaCar) contents.get(HumanContentsContainer.CAR);
// }
}
So how do I replicate the getCar().addMiles(x) method using a traditional getter without actually creating a getter?
Please note I also don't want to do this (below code): Because again, not worth it over a getter then:
public void addCarMiles(int num){
((ToytotaCar)contents.get(HumanContentsContainer.CAR).addMiles(num);
}
Looking for some easy kind of usage like:
human.getContentsThatIsIntanceOf(ToyotaCar).addMiles(1);
But don't know what getContentsThatIsInstanceOf would look like
I would go with:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private ToyotaCar car;
public void setCar(ToyotaCar car){
this.car = car;
}
public int getCar(){
return car;
}
public void addCarMiles(int num){
getCar().addMiles(num);
}
public Map<HumanContentsContainer, Object> getContents(){
Map<HumanContentsContainer, Object>map = new HashMap();
map.put(CAR,this.car );
//same for all the shoes and clothes and whatever the Human has
}
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
switch (c){
case CAR:{
this.car=c.getContainer();
}
}
//and so on
}
}
}
Edit
If you need to have a dynamic set of capabilities, I would suggest that you indeed keep the map of objects, and get rid of the ‘addCarMiles‘ method, as it implies that every human has a car.
I would implement public method on human ‘performCommand(CapabilityType, CapabilityCommand)‘ where the command will receive the capability and perform the operation on it. You may check out the Command Pattern tutorials.
Edit 2:
If all you want is to create a getter which will return dynamic type, you can use generics.
import java.io.Serializable;
import java.util.HashMap;
import java.util.NoSuchElementException;
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private HashMap<Class, Object> contents;
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
contents.put(c.getContainer().getClass(), c.getContainer());
}
}
public HashMap<Class, Object> getContents(){
return contents;
}
public <T> T getContentsThatIsIntanceOf(Class<T> type){
Object object = contents.get(type);
if (object==null){
throw new NoSuchElementException("No such element: "+type.getName());
}
return type.cast(object);
}
public void usageExample(){
this.getContentsThatIsIntanceOf(ToyotaCar.class).addMiles(10);
}
}

accessing elements of a linked list that is made up of a private custom class

in a project i am trying to get two or more agents to communicate between each other to collect things in the environment. to do this i am using a mailbox containing messages that they would respond to depending on the messages sent ebtween each other. below is where i create the linked list
mailbox = new LinkedList[numberOfAgents()];
for ( int i=0; i< numberOfAgents(); i++ ){
mailbox[i] = new LinkedList<Message>();
mailbox[i].add(new Message(i, knownBloodBanks, knownDonors));
}
and then the private message and intention classes
private class Message
{
// instance variables
private int senderId;
private BoardComponentList donors;
private BoardComponentList bloodBanks;
private BoardComponent requestAssistanceAt;
private Intention iIntendToAssistAt;
public Message( int senderId, BoardComponentList d, BoardComponentList b )
{
this.senderId = senderId;
donors = d;
bloodBanks = b;
} // end constructor
public void setIntentions( Intention intention )
{
iIntendToAssistAt = intention;
}
public void setRequest( BoardComponent bC )
{
requestAssistanceAt = bC;
}
public BoardComponentList getDonors()
{
return donors;
}
public BoardComponentList getBloodBanks()
{
return bloodBanks;
}
public Intention getIntentions()
{
return iIntendToAssistAt;
}
public BoardComponent getRequest()
{
return requestAssistanceAt;
}
public int getSenderId()
{
return senderId;
}
} // end Message class
private class Intention
{
// instance variables
private BoardComponent target;
private double distanceTo;
public Intention( BoardComponent bC, double distance )
{
target = bC;
distanceTo = distance;
} // end constructor
public BoardComponent getTarget()
{
return target;
}
public double getDistancetoTarget()
{
return distanceTo;
}
}
i cant for the life of me figure out how to access the methods inside the private class so that i can set goals and see the messages between agents. any help or pointers in the right direction would be greatly appreciated, i hope i've included enough info if not please let me know anything else needed
i didnt explain myself clearly as i so often find problems with but yes both the private classes and the first code snippet are found inside a public class
There can be only one public class per file.
The name of the file name(program name) should match with the name
of the pubic class.
There can be multiple private classes inside your public class as
inner classes.
Sample code below ( modified your classes a bit because they we giving compilation error):
package com.pkg1;
import java.util.LinkedList;
public class Sample{
public Sample(){
LinkedList[] mailbox = new LinkedList[10];
for ( int i=0; i< 10; i++ ){
mailbox[i] = new LinkedList<Message>();
mailbox[i].add(new Message(i));
}
}
private class Message
{
// instance variables
private int senderId;
private Intention iIntendToAssistAt;
public Message( int senderId )
{
this.senderId = senderId;
} // end constructor
public void setIntentions( Intention intention )
{
iIntendToAssistAt = intention;
}
public Intention getIntentions()
{
return iIntendToAssistAt;
}
public int getSenderId()
{
return senderId;
}
} // end Message class
private class Intention
{
// instance variables
private double distanceTo;
public Intention( double distance )
{
distanceTo = distance;
} // end constructor
public double getDistancetoTarget()
{
return distanceTo;
}
}
}

#GroupSequenceProvider and group is a superset

Simple class Person.class
class Person {
#NotNull(groups = {PartlyCheck.class})
private String name;
#NotNull(groups = {FullCheck.class})
private String adress;
private boolean isFullCheck;
}
Check interfaces
public interface PartlyCheck{}
public interface FullCheck extends PartlyCheck{}
I use two approach:
if(person.isFullCheck) {
validator.validate(person, FullCheck.class);
else {
validator.validate(person, PartlyCheck.class);
}
1.
If isFullCheck=true used both checks (FullCheck.class and PartlyCheck.class)
If isFullCheck=false used only PartlyCheck.class.
It is an understandable behavior.
#GroupSequenceProvider(PersonGroupSequenceProvider.class)
#Override
public List<Class<?>> getValidationGroups(Person person) {
List<Class<?>> defaultGroupSequence = new ArrayList<>();
defaultGroupSequence.add(Person.class);
if (person.isFullCheck) {
defaultGroupSequence.add(FullCheck.class);
} else {
defaultGroupSequence.add(PartlyCheck.class);
}
return defaultGroupSequence;
}
In the second case, I added #GroupSequenceProvider(PersonGroupSequenceProvider.class).
If isFullCheck=true used only FullCheck.class.
Why extends is not considered for this case?
If isFullCheck=false used only PartlyCheck.class.

Java Generics Wildcards Type Mismatch

I have the following structure:
public abstract class BaseVersionedEntity {
private long id;
private List<BaseRevision<? extends BaseVersionedEntity>> versions;
public BaseRevision<? extends BaseVersionedEntity> getLatestRevision() {
return versions.get(versions.size() - 1);
}
public abstract BaseRevision<? extends BaseVersionedEntity> newRevision();
}
public abstract class BaseVersionedEntityData<E> {
private long id;
private BaseRevision<E> revision;
}
public abstract class BaseRevision<E> implements Comparable<BaseRevision<E>> {
private long id;
private Timestamp timestamp;
private E versionedEntity;
private BaseVersionedEntityData<E> versionedEntityData;
public BaseVersionedEntityData<E> getVersionedEntityData() {
return versionedEntityData;
}
}
That will be implemented by this:
public class PersonEntity extends BaseVersionedEntity {
#Override
public BaseRevision<? extends BaseVersionedEntity> newRevision() {
PersonRevision newRevision = new PersonRevision();
newRevision.setTimestamp(new Timestamp(System.currentTimeMillis()));
getRevisions().add(newRevision);
return newRevision;
}
}
public class PersonData extends BaseVersionedEntityData<PersonEntity> {
}
public class PersonRevision extends BaseRevision<PersonEntity> {
}
Somewhere in my code i'll do the following call:
// is not null
PersonEntity personEntity;
PersonData personData = personEntity.getLatestRevision().getVersionedEntityData();
Out of some reasons that is marked with a type mismatch...
Type mismatch: cannot convert from BaseVersionedEntityData<capture#1-of ? extends BaseVersionedEntity> to PersonData
Can anyone find a mistake?? Or have any hints??
Thank you!!
Benjamin
The method getLatestRevision does not return a PersonRevision, it returns a BaseRevision, and even then PersonRevision doesn't return PersonData - you'll need an explicit cast since this is a downcast, and not even one of the "safe" caused-by-type-erasure downcasts:
PersonData personData = (PersonData)(personEntity.getLatestRevision().getVersionedEntityData());

Categories