ArrayIndexOutOfBoundsException while printing a TreeSet - java

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.

Related

How to do validation for set boolean and double

I just start to learn java recently, i got 1 problem about the validation for setter, refer below is the setter validation for string type , what should i should i write to do the setter validation for boolean and double? below is the code i wrote for string.
public class Person
{
private String name;
private String id;
private boolean isNew;
private double bonus
public Person()
{
this("Unknown","unknown",true,0.0);
}
public Person(String id,String name,boolean isNew,double bonus)
{
setId(id);
setName(name);
setIsNew(isNew);
setBonus(bonus);
}
public getId()
{
return id;
}
public getName()
{
return name;
}
public setId()
{
this.id = id;
}
public setName()
{
this.name = name;
}
public void display()
{
System.out.println("Id:" + id);
System.out.printoutln("Name:" + name);
}
// setter validation for string
public void setName(String name)
{
if(name == null)
{
throw new IllegalArgumentException("A valid name must be provided ");
}
name = name.trim();
if(name.length() ==0)
{
throw new IllegalArgumentException("Name must not be blank ");
}
this.name = name;
}
// setter validation for id
public void setId(String id)
{
if(id == null)
{
throw new IllegalArgumentException("A valid id must be provided ");
}
id = id.trim();
if(id.length() ==0)
{
throw new IllegalArgumentException("Id must not be blank ");
}
this.id = id;
}
}
I just start to learn java recently, i got 1 problem about the validation for setter, refer below is the setter validation for string type , what should i should i write to do the setter validation for boolean and double?
When you want return value you have to declare returned type for example "public String getId()" instead "public getId()".
Setter expects a parameter. Example: "public setId(String id)".
All args constructor should looks like:
public Person(String name, String id, boolean isNew, double bonus) {this.name = name; this.id = id;this.isNew = is;this.bonus = bonus; }
For boolean argument constructor expect value. If you want validate something you can change type to Boolean and handle NullPointerExeption.
Or create custom exception:
public class MyWrongBooleanException extends RuntimeException
{
public IncorrectFileExtensionException(String errorMessage, Throwable err)
{
super(errorMessage, err);
}
}

How to map enums to integers implicitliy

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;
}
}

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());
}

NullPointerException on array with length one initializing

This is my method to updateHighScoreRecords():
public GameRecord[] updateHighScoreRecords(GameRecord[] highScoreRecords, String name, int level, int score) {
GameRecord[] gameRecord = null;
if (highScoreRecords.length == 0) { // Rule one
gameRecord = new GameRecord[1];
gameRecord[0].setName(name);
gameRecord[0].setLevel(level);
gameRecord[0].setScore(score);
System.out.println("Role one Done");
}
return gameRecord;
}
And this is my GameRecord class:
public class GameRecord {
private String name;
private int level;
private int score;
public GameRecord(String name, int level, int score) {
this.name = name;
this.level = level;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
But there is a nullPointer exception on this line:
gameRecord[0].setName(name);
Why?
I want to return an array of GameRecord type when highScoreRecords length is zero.
You never initialized zeroth element. First you have to add element at zero position and then access it.
gameRecord[0] = new GameRecord();
gameRecord[0].setName(name);
When you wrote
gameRecord = new GameRecord[1];
That means you are just initializing an array to store 2 GameRecord elements. Nothing else. Initially those are null's. You need to initialize each element to use them further. Otherwise they are still null.

Is validating fields in both constructor and setter considered bad redundant code?

I have the following class :
public class Project {
private int id;
private String name;
public Project(int id, String name) {
if(name == null ){
throw new NullPointerException("Name can't be null");
}
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
this.name = name;
this.id = id;
}
private Project(){}
public int getId() {
return id;
}
public void setId(int id) {
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
this.id = id;
}
public String getName()
return name;
}
public void setName(String name) {
if(name == null ){
throw new NullPointerException("Name can't be null");
}
this.name = name;
}
}
If you noticed that setName and setId share the same validation for its fields with the constructor. Is this redundant code that could cause issues in the future ( for example if somebody edit the the setter to allow 0 for the id and prevent -1 instead but didn't change the constructor) ? . Should I use a private method to do the check and share it between the constructor and the setter which seems too much if there's a lot of fields.
Note: This is why im not using the setters in the constructor. https://stackoverflow.com/a/4893604/302707
Here is the revised code:
public class Project {
private int id;
private String name;
public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
checkId(id);
checkName(name);
//Insted of lines above you can call setters too.
this.name = name;
this.id = id;
}
private Project(){}
public int getId() {
return id;
}
public void setId(int id) {
checkId(id);
this.id = id;
}
public String getName()
return name;
}
public void setName(String name) {
checkName(name);
this.name = name;
}
private void checkId(int id){
if(id == 0 ){
throw new IllegalArgumentException("id can't be zero");
}
}
private void checkName(String name){
if(name == null ){
throw new NullPointerException("Name can't be null");
}
}
}
I recommend that you should define one method per field as isValid() and then call the same method in you setter as well as Constructor.
I would say yes. Rather than that, just call the setters from your constructor:
public Project(int id, String name, Date creationDate, int fps, List<String> frames) {
setName(name);
setId(id);
// other stuff with creationDate, fps and frames?
}
Also, you shouldn't check for a null name in getName -- do it in setName. Otherwise, bugs are going to be hard to track down -- you want to catch the invalid name as soon as it comes in, not when it's used (which may be much later).
if you make Project immutable, it will eliminate the redundant code. but for now, i think explicitly throwing exceptions in both the constructor and mutator methods is fine.
and i would not call the mutator methods within the constructor for many reasons, including this. also, i would remove the validation code in the accessor method...it's not necessary.

Categories