How to map enums to integers implicitliy - java

I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java
public enum Packets {
// Maps enums to integers 0-3
PACKET_NONE = 0, PACKET_SYNC,
PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,
// Maps enums to integers 13-16
PACKET_FILL = 13, PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}
I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

In Java you can assign values to Enum if that's what you are looking for. It will look like this:
public enum Packets {
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3);
private int value;
Packets(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
Now you can call enum like this to get it's value:
Packets.PACKET_SYNC.getValue(); //It will return 1

You can add a field to your enum, intialize this field in the enumeration constant's constructor call and then return this field from a public getter. This should look about like this:
public enum Packets
{
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3),
PACKET_FILL(13),
PACKET_GLASS(14),
PACKET_FILLI(15),
PACKET_GLASSI(16);
private final int id;
private MyEnum(final int id) {
this.id = id;
}
public final int getId() {
return index;
}
}

This is not that clean of a solution but if you really want to auto-initialize them to increment the same way the C++ declaration does, without explicitly defining each individual ID, you can do something like this:
public enum Packets
{
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3),
PACKET_FILL(13),
PACKET_GLASS(),
PACKET_FILLI(),
PACKET_GLASSI();
private int id;
private Packets(int id) {
this.id = id;
}
private Packets(){
this.id = -1;
}
public final int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
public static void initIds(){
for(Packets p : Packets.values()){
if(p.getId()==-1){
if(p.ordinal()==0){
p.setId(0);
}else{
p.setId(Packets.values()[p.ordinal()-1].getId()+1);
}
}
}
}
}
Then you call the initialize and it will fill in the ID's for you:
Packets.initIds();
System.out.println(Packets.PACKET_AVAIL_1.getId()); //3
System.out.println(Packets.PACKET_GLASS.getId()); //13
System.out.println(Packets.PACKET_FILL.getId()); //14
System.out.println(Packets.PACKET_FILLI.getId()); //15
edit/addition:
If you move the code from the initIds()method into a static initializer block, you do not need the initialize call somewhere in your code:
public enum Packets {
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3),
PACKET_FILL(13),
PACKET_GLASS(),
PACKET_FILLI(),
PACKET_GLASSI();
static {
for (Packets p : Packets.values()) {
if (p.getId() == -1) {
if (p.ordinal() == 0) {
p.setId(0);
} else {
p.setId(Packets.values()[p.ordinal() - 1].getId() + 1);
}
}
}
}
private int id;
private Packets(int id) {
this.id = id;
}
private Packets() {
this.id = -1;
}
public final int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

Related

ArrayIndexOutOfBoundsException while printing a TreeSet

I want to create a Treeset for abstract class. When I'm trying to print the value for the [0] in the treeset the output is giving 1 correctly but the output for [1] it is giving error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
Can someone please help me resolve this?
public abstract class E implements Comparable<E>{
private int Id;
private String name;
public E(int Id, String name) {
this.Id = Id;
this.name = name;
}
int id;
public int compareTo(E b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
public int getId() {
return Id;
}
public String Name() {
return name;
}
}
In your compareTo method inside Employee class you should compare empId, not this int id that you creating and never initializing.

How do I remove objects from an arraylist which are present in another arraylist based on one member variable of the object in Java?

I have a POJO class A with the below structure
class A{
private String var1;
private int var2;
private String var3;
}
I have two ArrayList<A> List1 and List2 with different size. I want to remove all elements in List1 which are already present in List2 and this equality needs to be checked with respect to the value stored in var2.
I have already checked making the List a Hashset and using removeAll(). But this wont give the desired output since for the same var2, var1 values differ.
Please help me solve this problem.
Edit 1 - Requested by Murat
public class HistoryDto implements Serializable,Comparable<HistoryDto> {
private Integer id;
private String sId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSId() {
return sId;
}
public void setSId(String sId) {
this.sId = sId;
}
public String getTrackName() {
return trackName;
}
public void setTrackName(String trackName) {
this.trackName = trackName;
}
public String getTrackDescription() {
return trackDescription;
}
public void setTrackDescription(String trackDescription) {
this.trackDescription = trackDescription;
}
public Integer getUsedNo() {
return usedNo;
}
public void setUsedNo(Integer usedNo) {
this.usedNo = usedNo;
}
public String getExtraInfo() {
return extraInfo;
}
public void setExtraInfo(String extraInfo) {
this.extraInfo = extraInfo;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getPartyId() {
return partyId;
}
public void setPartyId(Integer partyId) {
this.partyId = partyId;
}
private String trackName;
private String trackDescription;
private Integer usedNo;
private String extraInfo;
private String imageUrl;
private Integer partyId;
public int compareTo(HistoryDto other) {
return this.sId.compareTo(other.sId);
}
}
Removing Items
ListA.removeAll(new HashSet(listB));
You need 2 loops nested.
pseudocode:
for each in A do
for each in B do
if (current item of A equals to current item of B)
say yes!
done
done
You just need to translate it to Java.
You may do it using the Stream API:
Set<Integer> var2 = list2.stream()
.map(a -> a.var2)
.collect(Collectors.toSet());
list1.stream()
.filter(a -> !var2.contains(a.var2))
.collect(Collectors.toList());

Settings Relationship Properties in Neo4J OGM

I found out about Neo4j OGM yesterday and quickly made a new project to test out how it works. One problem I've come across is setting Relationhip properties as this is crucial for my project. Here's an example:
Room Node:
#NodeEntity
public class Room {
#GraphId
Long id;
#Property(name="name")
String name;
#Relationship(type="CONNECTS")
List<Room> rooms;
public List<Room> getRooms() {
if(rooms == null)
rooms = new ArrayList<Room>();
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
public Room(String name){
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Room(){
}
public void connectsTo(Room room){
this.getRooms().add(room);
}
}
Connects Node (Relation):
#RelationshipEntity(type="CONNECTS")
public class Connects {
#GraphId
Long id;
#StartNode
Room startMapNode;
#EndNode
Room endMapNode;
#Property(name="length")
int length;
public Connects(Room startMapNode, Room endMapNode){
this.startMapNode = startMapNode;
this.endMapNode = endMapNode;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Room getStartMapNode() {
return startMapNode;
}
public void setStartMapNode(Room startMapNode) {
this.startMapNode = startMapNode;
}
public Room getEndMapNode() {
return endMapNode;
}
public void setEndMapNode(Room endMapNode) {
this.endMapNode = endMapNode;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Connects(){
}
}
Main method:
public static void main(String[] args) {
SessionFactory sessionFactory = new SessionFactory("at.htl.in110010.domain");
Session session = sessionFactory.openSession("http://localhost:7474");
session.purgeDatabase();
Room roomOne = new Room("TEST_ROOM_ONE");
Room roomTwo = new Room("TEST_ROOM_TWO");
roomOne.connectsTo(roomTwo);
roomTwo.connectsTo(roomOne);
Connects connectRelation = new Connects(roomOne,roomTwo);
connectRelation.setLength(2);
session.save(connectRelation);
}
Now as you can see I've set the length in my main method, but when I check the database under http://localhost:7474 it shows the relation between the nodes but says it has no properties.
Here is the console output: http://pastebin.com/CByfmVcR
Any help in setting the Property would be very appreciated.
Or is there perhaps a different/easier way of mapping objects to the neo4J database ?
Thanks
Using a relationship entity is the right thing to do as you have properties on the relationship. But this also means that your relationship between rooms is represented by Connects.
So, Room should have a reference to Connects rather than to the other Room directly.
e.g.
#Relationship(type="CONNECTS")
List<Connects> rooms;
Here's a test that resembles your domain model:
https://github.com/neo4j/neo4j-ogm/tree/master/src/test/java/org/neo4j/ogm/domain/friendships and
https://github.com/neo4j/neo4j-ogm/blob/master/src/test/java/org/neo4j/ogm/integration/friendships/FriendshipsRelationshipEntityTest.java
I notice you're using neo4j-ogm 1.1.3. Please upgrade to 1.1.4 as it contains important fixes.

PriorityQueue order is not correct JAVA

I do have a User class which implements Comparable. After I add list of users into PriorityQueue<User> they should be prioritized by scores, but for some reason they don't. Could you please help me to figure out why users are not sorted in my Queue?
Update:
I am accessing queue by polling elements. prioritisedUsers.poll() it always comes with random scores with order respect.
PriorityQueue<User> prioritisedUsers = userPriorityStrategy.computeUserPriority(users);
while(!prioritisedUsers.isEmpty()){
System.out.println(prioritisedUsers.poll().getPriorityScore());
}
OUTPUT:
0.35036433736768735
0.6619121139678329
0.09520067929838127
0.4013591573863
0.6704568389588227
0.5989900926939181
0.7320779721160738
Thanks for any help!
public class User implements Comparable<User>{
private long id;
private String fistName;
private String lastName;
private double priorityScore;
public User (long id, String firstName, String lastName){
this.id = id;
this.fistName = firstName;
this.lastName = lastName;
}
public double getPriorityScore(){
return this.priorityScore;
}
public void setPriorityScore(double priorityScore){
this.priorityScore = priorityScore;
}
public long getId(){
return this.id;
}
public String getFistName(){
return this.fistName;
}
public String getLastName(){
return this.lastName;
}
public int compareTo(User o) {
return (int) (this.getPriorityScore() - o.getPriorityScore());
}
}
public PriorityQueue<User> computeUserPriority(List<User> users) {
PriorityQueue<User> prioritisedUsers = new PriorityQueue<User>(users.size());
for (User user : users) {
user.setPriorityScore(rand.nextDouble());
prioritisedUsers.add(user);
}
return prioritisedUsers;
}
I'm not so sure that your cast to (int) works well... because casting to an int implicitly drops any decimal.
If I'm not in wrong, try something like
public int compareTo(User object) {
if (this.getPriorityScore() < object.getPriorityScore())
return -1;
if (this.getPriorityScore() == object.getPriorityScore())
return 0;
return 1;
}
or alternatively and more simply:
public int compareTo(User o) {
return Double.compare(this.getPriorityScore(), o.getPriorityScore());
}

can't deserialize guava type with GWTP-Rest + jackson-guava from Spring service using guava-datatype

I use GWTP-Rest and i need to deserialize an dto which contains an ListMultimap. All the elements of the dto are deserialize but not the ListMultimap. below the code of dto. JsonAnnotation are working and come from the correct artifactId which is compatible with gwt-jackson. I imports with maven gwt-guava-jackson and inherits the module.
public class GetdtoMobileResult implements ExpirableResult, DtoData {
#JsonProperty("diffusions")
private ListMultimap<Integer, Diffusion> diffusions;
private TimeInterval visibleRange;
#JsonProperty("ttl")
private long ttl;
private dtoHourRange hourRange;
GetTVGuideMobileResult() {
super();
}
public GetTVGuideMobileResult(
final ArrayListMultimap<Integer, Diffusion> diffusions,
final TimeInterval visibleRange, final long ttl, final MediamatHourRange range) {
super();
this.diffusions = diffusions;
this.visibleRange = visibleRange;
this.ttl = ttl;
this.hourRange = range;
}
#JsonIgnore
#Override
public ListMultimap<ChannelId, Diffusion> getDiffusions() {
return ArrayListMultimap.create();
}
#JsonProperty("diffusions")
public ListMultimap<Integer, Diffusion> getdiffusions()
{
return diffusions;
}
#Override
public TimeInterval getVisibleRange() {
return visibleRange;
}
#JsonProperty("ttl")
#Override
public long ttl() {
return ttl;
}
#Override
public dtoHourRange getHourRange() {
return hourRange;
}
// #### setter add to able deserialization on client side mobile. ######
#JsonProperty("diffusions")
public void setDiffusions(final ListMultimap<Integer, Diffusion> diffusions) {
this.diffusions = diffusions;
}
public void setHourRange(final dtoHourRange hourRange) {
this.hourRange = hourRange;
}
#JsonProperty("ttl")
public void setTtl(final long ttl) {
this.ttl = ttl;
}
public void setVisibleRange(final TimeInterval visibleRange) {
this.visibleRange = visibleRange;
}
}
I receive the correct object from server {"diffusions":{"..."} ,...}. Serialization is doing by the lib jackson-datatype-guava, which if i correctly understood is using by jackson-guava. Interface which are implements define getter of the object, and implements Serializable.
I have another problem's, probably linked to his, my ListMultimap use normaly an dto as key which wrap an integer, but jackson tell me that my dto is not supported as map's key. Code of my dto :
public class DtoId implements Serializable {
/**
* serial version Uid
*/
private static final long serialVersionUID = -5816632906385308130L;
private int id;
DtoId() {
// for serialization
}
public DtoId(final int id) {
super();
this.id = id;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
#Override
public String toString() {
return Integer.toString(id);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ChannelId other = (ChannelId) obj;
if (id != other.id) {
return false;
}
return true;
}
}
Ok, problem's come from bad dependency between project on guava. I provided same version of guava to the client, shared & server, now serialization works, sorry to the bad question.
Second error continue to occurs, i will post this on an other page.

Categories