How to access the fields of an object in java? - java

I apologize, this question has already been answered once. However, the solution didn't help me.
I made a program working with an ArrayList containing name,ID and country. However, I cannot access the name, ID and country on their own, only their object as a whole. I tried using animal.name and I get the error name cannot be resolved or is not a field. I tried using methods like getName() to return the name of the object, but I got the error The method getName() is undefined for the type ArrayList<ANIMAL>. Would you please help me with that?
This is the class which, when called, creates a new object inside the ArrayList and fields of which I'm trying to access:
import java.io.*;
public class ANIMAL implements Serializable {
String nameA;
String IDA;
String countryA;
public ANIMAL(String name, String ID, String country){
nameA = name;
String IDA = ID;
String countryA = country;
}
public String getName(){
return nameA;
}
public String getCountry(){
return countryA;
}
public String getID(){
return IDA;
}
}

Your animal class:
public class Animal {
private String name;
private String id;
private String country;
public Animal (String name, String id, String country){
this.name = name;
this.id = id;
this.country = country;
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public String getId(){
return id;
}
}
Pseudo application class (with main method for starting the application):
public class MyApp {
public static void main(String[] args) {
List<Animal> list = new ArrayList<>();
list.add(new Animal("British Bulldog", "12345", "UK"));
list.add(new Animal("Boston Terrier", "12346", "USA"));
list.add(new Animal("German Shepherd", "12347", "Germany"));
// this is a for-each loop but basically you just need
// to get an item from the list, list.get(i) would suffice
for (Animal a: list) {
System.out.println(a.getName());
}
}
}
Prints:
British Bulldog
Boston Terrier
German Shepherd
Also: I took the liberty of tidying up your code to match conventions, look at the differences and try to understand them.

Your constructor was flawed.
import java.io.*;
public class ANIMAL implements Serializable {
String name;
String ID;
String country;
public ANIMAL(String name, String ID, String country){
this.name = name;
this.ID = ID;
// String IDA = ID; doesn't assigns param ID to field ID of the class
this.country = country; //same
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public String getID(){
return ID;
}
}
Hope this helps.

Related

Sort object list based on custom object as one of field [duplicate]

This question already has answers here:
Java 8: sort list of objects by attribute without custom comparator
(3 answers)
java 8 stream for sorting a list of objects based on particular field
(3 answers)
Closed 2 years ago.
public class Employee {
private String name;
private String id;
private Address address;
public String getName() {
return name;
}
public Employee setName(String name) {
this.name = name;
return this;
}
public String getId() {
return id;
}
public Employee setId(String id) {
this.id = id;
return this;
}
public Address getAddress() {
return address;
}
public Employee setName(Address address) {
this.address = address;
return this;
}
}
public class Address{
public String streetName;
public String streetNumber;
public String getName() {
return streetName;
}
public Address setStreetName(String streetName) {
this.streetName = streetName;
return this;
}
public String getId() {
return id;
}
public Address setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
return this;
}
}
Employee is one of class as defined above and Address is one of data type for one of field for Employee. List needs to be sorted based on streetName which is part of address field of Employee.
This can be done using writing a custom comparator. I am looking for a way using java lambda to sort and get the sorted list?
You could create a comparator like below or the way #Hadi J does in the comment:
Comparator<Employee> byStreetName = (emp1, emp2) -> emp1.getAddress().getName().compareTo(
emp2.getAddress().getName());
and use it like :
myList.sort(byStreetName);
or if you are using streams
myList.stream().sorted(byStreetName)...

How do I go about creating the method?

I'm currently trying to create a class in java, to this specification:
I'm not sure how to create "ratings" since I'm seeing its using some
map function using the input of a string and an integer.
Here's my code so far:
public class Movie {
String ID;
String Name;
String Description;
String Genre[];
String Directors[];
String Actors[];
String Language;
String CountryOfOrigin;
}
Please create different objects for genre, director, actor and rating. It will be a best practice when you try to add more information to each entity.
Use access modifier "private" to each attribute and implement get,set methods as required.
Use ArrayLists instead of arrays to avoid resizing efforts when required.
import java.util.ArrayList;
import java.util.List;
public class Genre {
private int id;
private String name;
public Genre(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Director {
private int id;
private String name;
public Director(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Actor {
private int id;
private String name;
public Actor(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Rating {
private int value;
private String name;
public Actor(int value, String name) {
this.value = value;
this.name = name;
}
}
public class Movie {
private int id;
private String name;
private String description;
private List<Genre> generes;
private List<Director> directors;
private List<Actor> actors;
private String language;
private String countryOfOrigin;
pulic Movie(int id, String name, String description, String language, String countryOfOrigin){
this.id = id;
// set other variables
this.actors = new ArrayList<Actor>();
// create other lists
}
public void addGenere(Genre genere){
this.generes.add(genere);
}
// implement other add methods to lists
}

trouble with spark cassandra connector in java

I am trying to query cassandra from spark in java. Below is the code to fetch data but mapToRow method takes two parameter. first is class and second is ColumnMapper. How to get instance of the ColumnMapper class in java. Googling it recommends creating object of derived class JavaBeanColumnMapper but didn't find how JavaBeanColumnMapper class should be instantiated.
List<String> dates = Arrays.asList("2015-02-02","2015-02-08");
JavaRDD<DailyTaxlot> openTaxlots = CassandraJavaUtil.javaFunctions(sc).
cassandraTable("wedbush_praveen_testing", "cf_taxlots",CassandraJavaUtil.mapToRow(DailyTaxlot.class),).
where("openclosetag=?","Open").where("rundate IN",dates);
Any lead will be appreciated.
Have a look at the example from the spark-cassandra-connector here:
JavaApiDemo.java
In the example you can see how the Person bean class is defined. The API will instantiate it as needed for each row.
JavaRDD<Person> rdd = CassandraJavaUtil.javaFunctions(sc).cassandraTable("test", "people", mapRowTo(Person.class));
// Bean definition
public static class Person implements Serializable {
private Integer id;
private String name;
private Date birthDate;
public static Person newInstance(Integer id, String name, Date birthDate) {
Person person = new Person();
person.setId(id);
person.setName(name);
person.setBirthDate(birthDate);
return person;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
}

Spring MVC: RequestBody + ResponseEntity: How to return an object/entity without some of the obj fields

I want to see is there a better way to achieve this: currently, I have a User class, UserRequest class and UserResponse class, they are all very similar or subset of User.
class User{
long id;
String name;
String password;
String field1;
String[] array1;
}
class UserRequest{
String name;
String password;
}
class UserResponse{
long id;
String name;
String field1;
}
So instead of having 3 similar classes, can I limit the fields using User class for the ResponseEntity? or what would be a better way to achieve what i am trying to do without having all the similar classes?
public #ResponseBody ResponseEntity<UserResponse> login(#RequestBody #Valid UserRequest request) {
User user = userRep.findByPrimaryEmailLike(request.getPrimaryEmail());
return new ResponseEntity<UserResponse>(user.getSuccessLoginResponse(), HttpHeaderUtils.getHeader4Json(), HttpStatus.OK);
}
Depends on what your format and (de-)serialization handler is, but making the wild guess it's JSON via Jackson:
import org.codehaus.jackson.annotate.JsonIgnore;
class User {
long id;
String name;
String password;
String field1;
String[] array1;
#JsonIgnore
public String[] getArray1() {
return array1;
}
#JsonIgnore
public void setArray1(String[] array1) {
this.array1 = array1;
}
public String getField1() {
return field1;
}
#JsonIgnore
public void setField1(String field1) {
this.field1 = field1;
}
public long getId() {
return id;
}
#JsonIgnore
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
If you use a SpringMVC extension like Yoga, you can return only the User object, but customize the request to determine which fields are returned in the #ResponseBody. For example,
GET http://mydomain.com/user?selector=name,password
GET http://mydomain.com/user?selector=id,name,field1

Make pure immutable class

I have following classes :
Emp.java
final public class Emp {
private Integer id;
private String name;
private Department department;
public Emp(Integer id, String name, Department department) {
this.id = id;
this.name = name;
this.department = department;
}
public Department getDepartment() {
return department;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
}
Department.java
public class Department {
private Integer id;
private String name;
public Department(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
EmployeeTest.java
public class EmployeeTest {
public static void main(String args[]) {
Department dept1 = new Department(1, "dept1");
Emp emp = new Emp(1, "emp1", dept1);
emp.getDepartment().setName("dept2");
System.out.println("emp = "+emp);
}
}
Here Emp class is not purely an immutable class because somehow I am able to change the values of Department (as shown in the example).
What are the best possible changes which will make Emp class a pure Immutable class ?
In getters for non-primitive field, use this structure
public class Line {
private final Point start;
private final Point end;
public Line(final Point start, final Point end) {
this.start = new Point(start);
this.end = new Point(end);
}
public Point getStart() {
return new Point(start);
}
public Point getEnd() {
return new Point(end);
}
}
So, simply create new instance of department that is equals to previous
P.S. In my example you can see pure immutable class
EDIT:
Also you can add to Department class copy-contructor
public Department(final Department dep)
{ ... }
And to Employer
getDepartment()
{
return new Department(department);
}
See Efffective Java:
Item 15: Minimize mutability – 5 rules to follow.
Don’t provide any methods that modify the object’s state
Ensure that the class can’t be extended
Make all fields final
Make all fields private
Ensure exclusive acess to any mutable components
If you don't like removing setters and do initialization in a constructor, you can think about returning immutable (from the point of view of the Emp class) objects, which will web objects' copies, in getters (see https://stackoverflow.com/a/128712/1579085).
final public class Emp {
private Integer id;
private String name;
private Department department;
public Emp(Integer id, String name, Department department) {
this.id = id;
this.name = name;
this.department = (Department) department.clone();
}
public Department getDepartment() {
return (Department) department.clone();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
}
And implement the method clone() in Department (which will implement the interface Cloneable) of course.
This approach is suitable, if you need to be able to modify Department, but the objects of the Emp class should be safe from those outer modifications.
make all attributes final, and remove all setters
Implement clone() in Department and make Emp return a clone of department in getDepartment().
If references to Department used in constructing Emp are available after construction, then Emp's constructor should clone given Department.

Categories