I am working on a project where code gets automatically generated based upon an MySQL library. It is somewhat like JPA, but not quite.
This is an example bean:
public class TemplateBean implements Bean {
private Integer templateId;
private Integer businessPartnerId;
public TemplateBean(final Integer businessPartnerId) {
this.businessPartnerId = businessPartnerId;
}
private TemplateBean(final Object nullObject, final Integer templateId, final Integer businessPartnerId) {
this.templateId = templateId;
this.businessPartnerId = businessPartnerId;
}
public TemplateBean(final ResultSet rs) throws SQLException {
this(null, rs.getInt(1), rs.getInt(2));
}
public Integer getTemplateId() {
return templateId;
}
public void setTemplateId(final Integer templateId) {
this.templateId = templateId;
}
public Integer getBusinessPartnerId() {
return businessPartnerId;
}
public void setBusinessPartnerId(final Integer businessPartnerId) {
this.businessPartnerId = businessPartnerId;
}
#Override
public String toString() {
return "Template(" + templateId + ", " + businessPartnerId + ")";
}
}
Now I need it to implement equals() and hashCode(). I of course have access to all data that is available from SQL, so I think implementing equals() should be doable, but how am I going to create a good hashCode()?
Any tips will be appreciated.
I would like to suggest to use EqualsBuilder
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Person {
private String id;
private String name;
private String address;
private String phone;
private String version;
#Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object,);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
or
/*
* equal() method with exclude fields.
* it will neglect id and version fields.
*
* */
#Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object, "id", "version");
}
}
One very convenient way is to use the #EqualsAndHashCode annotation provided by Groovy. Using this is as simple as
#EqualsAndHashCode
public class TemplateBean implements Bean {
// implementation omitted
}
This will generate equals() and hashCode() methods based on the class' properties using an algorithm similar to the one outlined in the book Effective Java.
Because the annotation is implemented via an AST transformation, it can be used in Java or Groovy classes, though you will of course need the Groovy library on your classpath to use it.
Related
I think the title is self-descriptive but I will give an example to elaborate on my question. I have a DTO class with few fields (a CarDataTransferObj class in my example). In another class (let's call it class A) I need to create a new instance of that object few times, but with only one field updated (length field in my example). Given DTO must be immutable in class A. As there is "many" fields in the class CarDataTransferObj, I thought about following approach (to avoid repeating code in class A):
#Builder
public class CarDataTransferObj {
private Integer id;
private String color;
private String manufacturer;
private String model;
private String uniqueIdNr;
private Integer nrOfDoors;
private EngineType engineType;
private Integer length;
private Integer safetyLevel;
public static CarDataTransferObj newInstanceWithUpdatedLength(final CarDataTransferObj car, final Integer newLength) {
return CarDataTransferObj.builder()
.id(car.getId())
.color(car.getColor())
.manufacturer(car.getManufacturer())
.model(car.getModel())
.uniqueIdNr(car.getUniqueIdNr())
.nrOfDoors(car.getNrOfDoors())
.engineType(car.getEngineType())
.length(newLength)
.safetyLevel(car.getSafetyLevel())
.build();
}
}
For me it smells like a little anti-pattern usage of static factory methods. I am not sure whether it's acceptable or not, hence the question.
Is using static factory method in the presented way an anti-pattern, and should be avoided ?
In my searching, I didn't come across anyone calling this1 an anti-pattern.
However, it is clear that if you try to do this using a classic builder that is not specifically implemented to support this mode of operation .... it won't work. For instance, the example CarBuilderImpl in the Wikipedia article on the Builder design pattern puts the state into an eagerly created Car instance. The build() method simply returns that object. If you tried to reuse that builder in the way that you propose, you would end up modifying a Car that has already been built.
There is another problem you would need to worry about. In we modified the Wikipedia CarBuilder example to add actual wheels (rather than a number of wheels) to the Car being built, we have to worry about creating cars that share the same wheels.
You could address these things in a builder implementation, but it is unclear whether the benefits out-weigh the costs.
If you then transfer this thinking to doing this using a factory method, you come to a slightly different conclusion.
If you are doing this as a "one-off", that's probably OK. You have a specific need, the code is clunky ... but so is the problem.
If you needed to do this for lots of different parameters, or combinations of parameters, this is not going to scale.
If the objects that are created are mutable, then this approach is could be problematic in a multi-threaded environment depending on how you control access to the objects you are using as templates.
1 - There are no clear measurable criteria for whether something is an anti-pattern or not. It is a matter of opinion. Admittedly, for many anti-patterns, there will be wide-scale agreement on that opinion.
It seems a little inefficient to construct an entirely new instance via a builder every time you want to make a new copy with a small modification. More significantly, it sounds like the places where you need the class to be immutable are isolated to places like class A. Why not try something like this:
public interface ICarDataTransferObject {
public Integer GetId();
public String GetColor();
public String GetManufacturer();
public String GetModel();
public String GetUUID();
public Integer GetDoorCount();
public EngineType GetEngineType();
public Integer GetLength();
public Integer GetSafteyLevel();
}
public class CarDataTransferObject Implements ICarDataTransferObject {
private Integer _id;
private String _color;
private String _manufacturer;
private String _model;
private String _uniqueIdNr;
private Integer _nrOfDoors;
private EngineType _engineType;
private Integer _length;
private Integer _safetyLevel;
public Integer GetId() { return _id; }
public void SetId(Integer id) { _id = id; }
public String GetColor() { return _color; }
public void SetColor(String color) { _color = color; }
public String GetManufacturer() { return _manufacturer; }
public void SetManufacturer(String manufacturer) { _manufacturer = manufacturer; }
public String GetModel() { return _model; }
public void SetModel(String model) { _model = model; }
public String GetUUID() { return _uniqueIdNr; }
public void SetUUID(String uuid) { _uniqueIdNr = uuid; }
public Integer GetDoorCount() { return _nrOfDoors; }
public void SetDoorCount(Integer count) { _nrOfDoors = count; }
public EngineType GetEngineType() { return _engineType; }
public void SetEngineType(EngineType et) { _engineType = et; }
public Integer GetLength() { return _length; }
public void SetLength(Integer length) { _length = length; }
public Integer GetSafteyLevel() { return _safetyLevel; }
public void SetSafteyLevel(Integer level) { _safteyLevel = level; }
public CarDataTransferObject() {}
public CarDataTransferObject(ICarDataTransferObject other) { ... }
public ReadOnlyCarDataTransferObject AsReadOnly() {
return ReadOnlyCarDataTransferObject (this);
}
}
}
public class ReadOnlyCarDataTransferObject Implements ICarDataTransferObject {
private ICarDataTransferObject _dto = null;
public Integer GetId() { return _dto.GetId(); }
public String GetColor() { return _dto.GetColor(); }
public String GetManufacturer() { return _dto.GetManufacturer(); }
public String GetModel() { return _dto.GetModel(); }
public String GetUUID() { return _dto.GetUUID(); }
public Integer GetDoorCount() { return _dto.GetDoorCount(); }
public EngineType GetEngineType() { return _dto.GetEngineType(); }
public Integer GetLength() { return _dto.GetLength(); }
public Integer GetSafteyLevel() { return _dto.GetSafteyLevel; }
public ReadOnlyCarDataTransferObject (ICarDataTransferObject other) {
_dto = other;
}
}
Now when you want class A to have a copy no one can modify, just use the copy constructor and only expose a ReadOnly version of that copy.
public class A {
ICarDataTransferObject _dto;
ReadOnlyCarDataTransferObject _readOnlyDTO;
public ICarDataTransferObject GetDTO() { return _readOnlyDTO; }
public A(ICarDataTransferObject dto) {
_dto = new CarDataTransferObject(dto);
_readOnlyDTO = new ReadOnlyCarDataTransferObject(_dto);
}
}
You commonly see this approach in .NET applications.
While it is debatable whether your static method is an anti-pattern or not, it surely won't scale for combinations of different attributes. Nonetheless, even if it's not an anti-pattern, I think there is a better way to accomplish what you need.
There's a variant of the traditional builder pattern that, instead of creating a new empty builder, accepts an already built object and creates an already initialized builder. Once you create the builder this way, you simply change the length attribute in the builder. Finally, build the object. In plain code (no Lombok, sorry) it could be like this:
public class CarDataTransferObj {
private Integer id;
private String color;
// other attributes omitted for brevity
private Integer length;
// Private constructor for builder
private CarDataTransferObj(Builder builder) {
this.id = builder.id;
this.color = builder.color;
this.length = builder.length;
}
// Traditional factory method to create and return builder
public static Builder builder() {
return new Builder();
}
// Factory method to create and return builder initialized from an instance
public static Builder builder(CarDataTransferObj car) {
Builder builder = builder();
builder.id = car.id;
builder.color = car.color;
builder.length = car.length;
return builder;
}
// getters
public static class Builder {
private Integer id;
private String color;
private Integer length;
private Builder() { }
public Builder withId(Integer id) { this.id = id; return this; }
public Builder withColor(String color) { this.color = color; return this; }
public Builder withLength(Integer length) { this.length = length; return this; }
public CarDataTransferObj build() {
return new CarDataTransferObj(this);
}
}
}
Now with all this infrastructure in place, you can do what you want as easy as:
CarDataTransferObj originalCar = ... // get the original car from somewhere
CarDataTransferObj newCar = CarDataTransferObj.builder(originalCar)
.withLength(newLength)
.build();
This approach has the advantage that it scales well (it can be used to change any combination of parameters). Maybe all this builder's code seems boilerplate, but I use an IntelliJ plugin to create the builder with two keystrokes (including the variant factory method that accepts a built instance to create an initialized builder).
I'm still new to java but..
I guess making a copy method which takes the CarDataTransferObj object variables and sets their values to another CarDataTransferObj object variables and changing the the length using it's setter method would be better idea
Example:
public class CarDataTransferObj {
private Integer id;
private String color;
private String manufacturer;
private String model;
private String uniqueIdNr;
private Integer nrOfDoors;
private EngineType engineType;
private Integer length;
private Integer safetyLevel;
public void Copy(CarDataTransferObj copy) { //Could add another parameter here to be the new length
copy.setId(id);
copy.set(color);
copy.setManufacturer(manufacturer);
copy.setModel(model);
copy.setUniqueIdNr(uniqueIdNr));
copy.setNrOfDoors(nrOfDoors));
copy.setEngineType(engineType));
copy.setLength(length);
copy.setSafetyLevel(safetyLevel));
}
}
public class SomeOtherClass {
CarDataTransferObj car1 = new CarDataTransferObj(); //Using this way made you able to use the constructor for a more useful thing
//You set the variables you want for car1 here
CarDataTransferObj car2 = new CarDataTransferObj();
car1.Copy(car2)
car2.setLength(newLength) //Set the new length here
}
I'm currently making an package and class diagram. I have a class that uses the compareTo method. My question is when I model it, do I have to make a self association? If so, is the self association a dependency line or just a normal line?
Example of the code:
public class Example implements Comparable<Example> {
private String name;
public Example(String name) {
this.name = name;
}
public String getNaam() {
return name;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Example) {
return ((Example) obj).name.equals(name);
} else {
return false;
}
}
#Override
public int hashCode() {
return name.hashCode();
}
#Override
public int compareTo(Example o) {
return name.compareTo(o.getNaam());
}
#Override
public String toString() {
return name;
}
}
Because a class knows itself (which is self-evident) you simply write it this way:
Note: I left out most of the operations.
A self reference is used if you have an attribute which is typed with the class itself. A simple example is Employee which references a manager that is an Employee itself:
To elaborate on this: as you have seen, associations are just another rendering for attributes. If you use a typed parameter which is not represented by an attribute you would create a dependency like in the following picture.
firstly, pardon my pseudo-code, i think in this case it is more legible than full code. Please assume that a property in the pseudo-code is in fact a field with a getter & setter method, except for the ArticleElement where it just needs be a property accessible from the object either by a direct getter method, or a two step getter method (ie getArticleSource().getName()).
Say i have a template entity:
ArticleTemplate
Long id;
String name;
String description;
Integer amount;
Schedule schedule;
and it is used (via its schedule) to create many potential children entities on different dates:
Article
Long id;
String name;
String description;
Integer amount;
Date date;
Boolean complete;
ArticleTemplate template;
some children entities are not created from a parent, they can be stand-alone (template can be null).
for my UI I want to create a sorted & merged list of :
a) potential children entities from parent entities
b) real children entities previously created from parent entities
c) orphan children entities created stand-alone
however, I need to add some properties to the elements of this list to determine the differences between the elements:
ArticleElement
// actual value if from Article, null if from potential from ArticleTemplate
Long id;
// actual value if from Article or ArticleTemplate
String name;
// actual value if from Article or ArticleTemplate
String description;
// actual value if from Article or ArticleTemplate
Integer amount;
// actual value if from Article, simulated if from potential from ArticleTemplate
Date date;
// actual value if from Article, false if from potential from ArticleTemplate
Boolean complete;
// actual value (nullable) if from Article, self if from potential from ArticleTemplate
ArticleTemplate template;
// false if from Article, true if from potential from ArticleTemplate
Boolean templateSimulation;
// once the list is sorted, a running tally of this.amount is to be stored on this object
Integer runningTally;
// would be type of interface if Article and ArticleTemplate implement same
Object source;
Clearly I'm going to have at least 3 classes but there's a few different approaches with interfaces etc.
I'd like to avoid cloning and property copying wherever possible, and use inheritence wherever beneficial.
suggestions appreciated!
p.
Here's my current solution, and i'm not sure I like it, but i haven't come up with anything better just yet:
firstly, i'll leave Article and ArticleTemplate alone. I could make them implement an interface describing their similarities but it doesn't add much benefit for this case.
create the UI contract
public interface UiElement<T>
{
T getSource();
Class<T> getType();
// redundant - refer to source
// Long getId();
String getName();
String getDescription();
Integer getAmount();
Date getDate();
Boolean getComplete();
// redundant - not needed anymore
// ArticleTemplate getTemplate();
// redundant - replaced by getType()
// Boolean getTemplateSimulation();
Integer getRunningTally();
}
create implementation for Article - pass through contracted calls to the source object for most properties
public class ArticleUiElement implements UiElement<Article>
{
private Article source;
private Integer tally;
public ArticleUiElement(Article source) {
this.source = source;
}
public Article getSource() {
return source;
}
public Class<Article> getType() {
return Article.class;
}
public String getName() {
return source.getName();
}
public String getDescription() {
return source.getDescription();
}
public Integer getAmount() {
return source.getAmount();
}
public Date getDate() {
return source.getDate();
}
public Boolean getComplete() {
return source.getComplete();
}
public String getRunningTally() {
return tally;
}
public void setRunningTally(String tally) {
this.tally = tally;
}
}
create implementation for ArticleTemplate - pass through contracted calls to the source object for most properties
public class ArticleTemplateUiElement implements UiElement<ArticleTemplate>
{
private ArticleTemplate source;
private Integer tally;
private Date date;
public ArticleTemplateUiElement(ArticleTemplate source) {
this.source = source;
}
public ArticleTemplate getSource() {
return source;
}
public Class<ArticleTemplate> getType() {
return ArticleTemplate.class;
}
public String getName() {
return source.getName();
}
public String getDescription() {
return source.getDescription();
}
public Integer getAmount() {
return source.getAmount();
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Boolean getComplete() {
return false;
}
public String getRunningTally() {
return tally;
}
public void setRunningTally(String tally) {
this.tally = tally;
}
}
can someone offer improvements, or an entirely better solution?
Recently I've started hearing about "POJOs" (Plain Old Java Objects). I googled it, but still don't understand the concept well. Can anyone give me a clear description of a POJO?
Consider a class "Person" with variables "id, name, address, salary" -- how would I create a POJO for this scenario? Is the code below a POJO?
public class Person {
//variables
People people = new People();
private int id;
private String name;
private String address;
private int salary;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getSalary() {
return salary;
}
public void setId() {
this.id = id;
}
public void setName() {
this.name = name;
}
public void setAddress() {
this.address = address;
}
public void setSalary() {
this.salary = salary;
}
}
A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:
Default no-arg constructor
Follow the Bean convention of getFoo (or isFoo for booleans) and setFoo methods for a mutable attribute named foo; leave off the setFoo if foo is immutable.
Must implement java.io.Serializable
POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.
The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.
Martin Fowler coined a new acronym.
Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.
Here's an example that you can wrap your head around:
public class MyFirstPojo
{
private String name;
public static void main(String [] args)
{
for (String arg : args)
{
MyFirstPojo pojo = new MyFirstPojo(arg); // Here's how you create a POJO
System.out.println(pojo);
}
}
public MyFirstPojo(String name)
{
this.name = name;
}
public String getName() { return this.name; }
public String toString() { return this.name; }
}
POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.
Properties of POJO
All properties must be public setter and getter methods
All instance variables should be private
Should not Extend prespecified classes.
Should not Implement prespecified interfaces.
Should not contain prespecified annotations.
It may not have any argument constructors
Example of POJO
public class POJO {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
A POJO is a Plain Old Java Object.
From the wikipedia article I linked to:
In computing software, POJO is an
acronym for Plain Old Java Object. The
name is used to emphasize that a given
object is an ordinary Java Object, not
a special object, and in particular
not an Enterprise JavaBean
Your class appears to already be a POJO.
POJO class acts as a bean which is used to set and get the value.
public class Data
{
private int id;
private String deptname;
private String date;
private String name;
private String mdate;
private String mname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMdate() {
return mdate;
}
public void setMdate(String mdate) {
this.mdate = mdate;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
}
When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.
Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.
Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.
According to Martin Fowler
The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.
Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.
Each variable in a POJO should be declared as private.
Default constructor should be overridden with public accessibility.
Each variable should have its Setter-Getter method with public accessibility.
Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).
And according to Java Language Specification, a POJO should not have to
Extend pre-specified classes
Implement pre-specified interfaces
Contain pre-specified annotations
However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.
A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
Read more on Plain Old Java Object (POJO) Explained.
there are mainly three options are possible for mapping purpose
serialize
XML mapping
POJO mapping.(Plain Old Java Objects)
While using the pojo classes,it is easy for a developer to map with the database.
POJO classes are created for database and at the same time value-objects classes are created with getter and setter methods that will easily hold the content.
So,for the purpose of mapping in between java with database, value-objects and POJO classes are implemented.
import java.io.Serializable;
public class Course implements Serializable {
protected int courseId;
protected String courseName;
protected String courseType;
public Course() {
courseName = new String();
courseType = new String();
}
public Course(String courseName, String courseType) {
this.courseName = courseName;
this.courseType = courseType;
}
public Course(int courseId, String courseName, String courseType) {
this.courseId = courseId;
this.courseName = courseName;
this.courseType = courseType;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseType() {
return courseType;
}
public void setCourseType(String courseType) {
this.courseType = courseType;
}
#Override
public int hashCode() {
return courseId;
}
#Override
public boolean equals(Object obj) {
if (obj != null || obj instanceof Course) {
Course c = (Course) obj;
if (courseId == c.courseId && courseName.equals(c.courseName)
&& courseType.equals(c.courseType))
return true;
}
return false;
}
#Override
public String toString() {
return "Course[" + courseId + "," + courseName + "," + courseType + "]";
}
}
public class UserInfo {
String LoginId;
String Password;
String FirstName;
String LastName;
String Email;
String Mobile;
String Address;
String DOB;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getMobile() {
return Mobile;
}
public void setMobile(String mobile) {
Mobile = mobile;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
}
File-setting-plugins-Browse repositories
Search RoboPOJOGenerator and install, Restart Android studio
Open Project and right click on package select on Generate POJO from JSON
Paste JSON in dialogbox and select option according your requirements
Click on Generate button
If a class is not bogged down from a framework or a library, then an object created from that class is recognized as a POJO.
Let's see some examples:
class MyServlet extends HttpServlet{
//....
}
The sole meaning of MyServlet class is given by the HttpServlet class. Therefore the objects created from the MyServlet are not POJOs.
class MyClass implements Serializable{
//...
}
The Serializable interface does not give a meaning to the class MyClass. Therefore the objects created from the MyClass are POJOs.
I have this Player class which implements the Comparable interface. Then I have an ArrayList of Players. I'm trying to use binarySearch() on the list of Players to find one Player, but Java is giving me a "cannot find symbol: method binarySearch(java.util.ArrayList< Player>,Player)".
This the Player class:
class Player implements Comparable {
private String username;
private String password;
Statistics stats;
//Constructor, creates a new Player with a supplied username
Player(String name) {
username = name;
password = "";
stats = new Statistics();
}
//Accessor method to return the username as a String
String getName() {
return username;
}
String getPassword() {
return password;
}
void setPassword(String newPass) {
password = newPass;
}
//Method to change the username
void setName(String newName) {
username = newName;
}
public int compareTo(Object o) {
return username.compareTo(((Player)o).username);
}
}
Weird thing, when I try Collections.sort() on this same list, it works.
Use are using generics inconsistently. Take heed of the compiler warnings. Always supply generic arguments (or never supply them).
Instead of:
class Player implements Comparable {
[...]
public int compareTo(Object o) {
Use
class Player implements Comparable<Player> {
[...]
public int compareTo(Player o) {
The rules of generics are difficult enough without the complication of rare types. So, typically the language spec gives up if you mix them up.
As long as you are implementing Comparable, you can make compareTo() consistent with equals() by also overriding equals() and hashCode(). This is particularly easy in this case, as you can simply delegate to String. Moreover, it's convenient if you ever need a Map containing instances of Player:
class Player implements Comparable<String> {
private String username;
private String password;
// ...
#Override
public int compareTo(String name) {
return username.compareTo(name);
}
#Override
public boolean equals(Object obj) {
return obj instanceof Player
&& username.equals(((Player)obj).username);
}
#Override
public int hashCode() {
return username.hashCode();
}
}