Finding index of more than one object - java

I create this code just for my own understanding. I have a person class and a List to store all my Person objects. I added the same object twice to illustrate my question. How do I find the index of those objects?
How do I find the indexes of the two Andy Bernards?
public class Person {
private String firstName;
private String lastName;
public Person(String firstName,String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override public String toString()
{
return String.format(this.firstName + " " + this.lastName);
}
}
List<Person> deletePeople = new ArrayList<Person>();
Person createPerson = new Person("Andy","Bernard");
Person createTwo = new Person("Micheal","Scott");
deletePeople.add(createPerson);
deletePeople.add(createTwo);
deletePeople.add(createPerson);
/* for (Person display : deletePeople) {
if(display.getFirstName().equals("Andy")) {
System.out.println(deletePeople.indexOf(display));
}
} */
}

Firstly, add .equals() and .hashCode() methods to class Person so you can identify a Person object as being the same.
Second, use indexOf() and lastIndexOf() methods in class List to find the first and last Andy Bernard objects.

If what you really want is a list of indexes into the list where objects match your criteria, and there can be more than one, then you will need to iterate the list yourself, and save the indexes to some sort of list.
If what you want is simply to delete the matching items, then you can use java.util.Iterator (see http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html) to iterate over the collection, and invoke the Iterator's remove() method on each matching object as you encounter it.

Related

Check if object with same properties exist - Static factory method

Using static factory method, I want to create objects (e.g. persons), but throw an error/exception if a person with the same criteria is being created.
I have 2 classes Person.java / Program.java (<-Main)
My static method is as follow:
public class Person{
private String firstName;
private String lastName;
private Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static Person fullName(String firstName, String lastName){
/*if(firstName.equals(this.firstName)){
System.out.println("Person already exists!");
}else{
return new Person(firstName,lastName);
}*/
return new Person(firstName, lastName);
}
}
Now obviously the commented-out part wouldn't work because Person isn't instanciated, but I'm kind of lost about how I could go on.
And yes, I'm overriding equals and hashcode!
To achieve it you should keep traces of all created instances in the Person class by using a static collection.
Note that it may cause memory retention if you don't use weak references for them and these are only referenced by the collection defined in Person.
Then about the check of an existing Person, as you overrided equals() and hashCode(), you could create a new Person from the parameters and check whether it was already created.
public class Person{
private String firstName;
private String lastName;
private static Set<Person> persons = new HashSet<>();
private Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
// equals and hashCode overrided relying on firstName and lastName fields
// ..
// Aditionnally to ease the creation of the exception message, override toString() too
#Override
public String toString(){
return "name=" + name +", lastName=" + lastName);
}
public static Person fullName(String firstName, String lastName){
Person p = new Person(firstName, lastName);
if (persons.contains(p)){
throw IllegalArgumentException("person " + p " already created";
}
persons.add(p);
return p;
}
}

How to print contents of Java object without using getters

Actually i am implementing one program in which i am retrieving information from database and i am setting that info to One Object using setters and i just want to print that Object parameters without using system.out.println(object.getHeadCount());
I just want like if i am giving system.out.println(object); so using this code it should print data in Json format or any other readable format.
How to do it.Because my object is containing 30 fields so it is very hectic to write 30 getters to print data.
You have to override toString()
Normal way
class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString(){
return this.firstName + " " + this.lastName;
}
}
Using Apache Commons
class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString(){
return new ToStringBuilder(this)
.append("firstName", firstName)
.append("lastName", lastName)
.toString();
}
}
Using Google Guava
class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString(){
return MoreObjects.toStringHelper(this)
.add("firstName", firstName)
.add("lastName", lastName)
.toString();
}
}
You simply have to override the toString() method of the class, read about it in java doc for Object class. Most IDE support it's automatic generation for all the fields of your class or for a number of them. Just for example:
class User {
private String name;
private String surname;
User(String name, String surname)
{
this.name = name;
this.surname = surname;
}
#Override
public String toString()
{
return this.name+" "+this.surname;
}
}
You should override toString() method. if you are using eclipse then you can try right-click within the editor, you'll find it under Source -> Generate toString()
To make a toString method you can simply just add one like so.
public String toString(){
return "" + getValue();
}
The toString method is a part of
java.lang.Object
So it is implemented in every class.

JAVA - HELP adding comparable interface and arrays into my class

I got a lab assignment dealing with arrays, sorting them and adding comparable interface to my two classes. I have to modify a Customer class so it implements a comparable interface. Then I have to sort an array of objects created by this class.
These are the steps outlined by my worksheet:
open the customer and SortedCustomersApp java files (see below):
public class Customer
{
private String email;
private String firstName;
private String lastName;
public Customer(String email, String firstName, String lastName)
{
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return email;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
}
This is the sorted customers app:
import java.util.Arrays;
public class SortedCustomersApp
{
public static void main(String[] args)
{
}
}
add code to the customer class to implement the comparable interface. The compareTo method you create should compare the email field of the current customer with the email field of another customer. To do that you cant use the < or > operators because the email field is a string. Instead, use the compareToIgnoreCase method of the string class. This method compares the string it's executed on with the string that's passed to it as an argument. If the first string is less than the 2nd string, this methods returns a negative integer. if the first string is greater than the second string, it returns a positive integer. And if the 2 strings are equal, it returns 0.
3.Add code to the SortedCustomersApp class that creates an array of Customer objects that can hold 3 elements, and create and assign Customer objects to those elements. Be sure that the email values you assign to the objects aren't in alphabetical order. Sort the array.
code a "for each" loop that prints the email, firstName, and lastName fields of each Customer object on a separate line.
compile and test the program
This program needs to have user input for email, firstName, and lastName but when I tried adding user input to the customer app I got errors saying I cant convert a string to scanner type, but the user inputs need to be a string so that's also a problem.
you implement Comaprable in order to define for Collections.sort() what criteria you use compare instances.For example if I was to compare students by their grades:
public class Student implements Comparable<Student>{
int age;
int grade;
//this method is used in Collections.sort() to determine what is bigger
//for me its grades that matter so that's what I do in code
#override
compareTo(Student other){
if(this.grade>other.grade){
return 1;
}else if(grade<other.grade){
return -1;
}
return 0;
}
}
then you just create an ArrayList students for example and call
Collections.sort(students)
EDIT: to answer you question in comments. If you use a Collection like ArrayList you would call Collections.sort() , if you use a regular array, then Arrays.sort(). In both cases the Objects to be sorted need to implement Comparable just like I showed you.
You can compare two String's lexicographically calling compareTo method on String object, code looks like this
public class Customer implements Comparable<Customer>{
private String email;
public Customer(String email) {
this.email = email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
#Override
public int compareTo(Customer otherCustomer) {
return this.email.compareToIgnoreCase(otherCustomer.email);
}
#Override
public String toString() {
return "Customer{" +
"email='" + email + '\'' +
'}';
}
}
You can sort list of objects using Collections.sort method
List<Customer> list = new ArrayList<>();
list.add(new Customer("abc#bc.com"));
list.add(new Customer("des#bc.com"));
list.add(new Customer("bbc#bc.com"));
list.add(new Customer("aec#bc.com"));
Collections.sort(list);
modified customer class
public class Customer implements Comparable<Customer>{
:
public int compareTo(Object obj)
{
Customer cus = (Customer) obj;
// write your comparison code here
// return 1, 0, or -1 on the basis of your requirement
}
:
}
Then perform
Collection.sort(customerList);
in main method to sort the data.
There is two ways to take String as an input from user:
1) Buffered Reader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String email = reader.readLine(); // email, firstname etc.
2) Scanner Class
Scanner input = new Scanner(System.in);
String email = input.next();
Now create an Customer object and add setter method to set the value.

Which of these ways is better in Java? [duplicate]

This question already has answers here:
Constructors vs Factory Methods [closed]
(10 answers)
Closed 8 years ago.
I want to create a static class which works like enumeration, but with string values.
Which of the following ways is the safest to extract a full instance of created class?
public class Name
{
public static final Name MY_NAME = new Name("Chris", "Doe");
public String firstName;
public String lastName;
public Name(firstname, lastname)
{
this.firstName = firstname;
this.lastName = lastname;
}
}
OR
public class Name
{
public String firstName;
public String lastName;
public Name(firstname, lastname)
{
this.firstName = firstname;
this.lastName = lastname;
}
public static Name myName()
{
return new Name("Chris", "Doe");
}
}
Safest? I'm not sure what you mean by that.
As far as best-practices go, the second is potentially wasteful, as it will allocate a new instance of Name every time myName() is invoked. The other uses a constant, so it conserves more memory.
All of which is relatively trivial in a small application.
If you're trying to have your class emulate an enum, the constant is certainly the way to go, as the values of an enum are initialized only once.
Just in case you don't know what an enum actually is, here would be a sample implementation of your class as one:
public enum Name {
MY_NAME ("Chris", "Doe");
private final String firstName;
private final String lastName;
private Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
... and you could then simply refer to Name.MY_NAME.
I would like to go with the first one, because the first one comprises of static final Name MY_NAME whereas in the second case a new Name instance would be returned everytime you call the myName() method resulting in wastage of memory. So, better go with the first one.
So, to extract a full-instance of a created class, you should go with the first one.
Also,talking about enum----in which you hold constant values, your static field final Name MY_NAME instance will serve the purpose, you should stick to the first-declaration----thereby supporting your need of enum as well as not wasting memory!
go after first method,
create your public static instances of class, make your class final so it cant be extended, and make constructor private, so it cannot be instantiate outside of your class
flaw with second method is, your static method myName each time creates new instance of Name which is unnecessary
If you only need one object instance with the fixed values why bother having member variables at all?
This way is thread safe regardless of how you use the object.
public class Name
{
public String getFirstName() {
return "Chris"
}
public String getFirstName() {
return "Doe"
}
}
If you must have member variables then:
public class Name
{
public final String firstName = "Chris"
public final String lastName = "Doe"
}
But as others have suggested just use the enum:
public enum Name {
me("Chris", "Doe");
private String firstName;
private String lastName;
Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

Get and set to private variables in java

Good day,
I am new to JAVA'm learning this language and what I have learned it seems a fantastic language. My question is in relation to the following:
Suppose I have a class like this:
public class Person{
private String firstName;
private String lastName;
private int age;
private String entireName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEntireName() {
return entireName;
}
public void setEntireName(String entireName) {
this.entireName = entireName;
}
public static void Main(String args[]){
Person person = new Person();
person.setFirstName("Jhon");
person.setLastName("Adams");
person.setAge(20);
//Atention this line
person.setEntireName(person.getFirstName()+person.getLastName());
}
}
The language allows me to do this: person.setEntireName(person.getFirstName()+person.getLastName());
and it works fine however I would like to know how is best to do this, how it behaves at the object level and how high or low the performance.
Thank you ..
What you do is perfectly valid, but not very logical. Why not just drop the setEntireName() since it just combines two existing fields?
public String getEntireName() {
return firstName + " " + lastname;
}
This is valid. There is no performance difference, becasue JIT compiler optimize this code if needed (simply replace method with fields access).
Typically it is easier to eliminate the entireName property and its setter, and use the getter to perform the concatenation like so:
public String getEntireName() {
return firstName + " " + lastName;
}
This is also easier to maintain than updating entireName every time firstName or lastName is changed.

Categories

Resources