Normally if we want to initialize a generic non-primitive ArrayList we do this
ArrayList<?> arrayList = new ArrayList<MyClass.class>();
But I want to do something similar to this no matter which class object I pass, i.e
private void getModel(Class responseType){
//Something similar, because this does not work..
ArrayList<?> arrayList = new ArrayList<responseType>();
}
Any Help would be greatly appreciated.
Try something like this
private <T> void setModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
}
If you want to get the list back then
private <T> ArrayList<T> getModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
EDIT
A FULL EXAMPLE SHOWING HOW TO USE GENERIC TYPE FOR ARRAYLIST
Tester class with main method and the generic Method
public class Tester {
private <T> ArrayList<T> getModels(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = (ArrayList<Data>) t.getModels(Data.class);
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = (ArrayList<Magic>) t.getModels(Magic.class);
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
Another possibility to use the same things without parameter since we don't use it inside the method
public class Tester {
private <T> ArrayList<T> getModel() {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = t.getModel();
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = t.getModel();
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
Model class (Data)
public class Data {
private Integer id;
private String name;
public Data() {
}
public Data(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
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;
}
#Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
Model class (Magic)
public class Magic {
private Integer id;
private String name;
public Magic() {
}
public Magic(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
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;
}
#Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
This works:
private void getModel(){
ArrayList<?> arrayList = new ArrayList<Object>();
}
I mean, it is unclear what you are trying to do. Generics is purely compile-timem, to perform compile-time type checking. Therefore, if the type parameter is not known at compile time, it would be useless.
Try using following
public <T> List<T> getList(Class<T> requiredType) {
return new ArrayList<T>();
}
public void useList() {
List<Integer> ints = getList(Integer.class);
List<String> lists = getList(String.class);
}
Related
I have two Java classes:
public class Request
{
private List<Item> subItems;
public Request()
{
}
public List<Item> getSubItems()
{
return subItems;
}
public void setSubItems(List<Item> subItems)
{
this.subItems = subItems;
}
}
class Item
{
private String name;
private String functionName;
//...elided...
}
The subItems that will be passed can be complex (include a function) or simple (just a name). There can be a mix of these. To simplify the JSON, I'd like to be able to accept the following:
JSON:
{
"subItems": [
{
"name": "complexType",
"function": "someFunction"
},
"simpleType"
]
}
and then have this turned into the equivalent of the following instance:
Request request = new Request();
request.setSubItems(
Arrays.asList(
new Item( "complexType", "SomeFunction" ),
new Item( "simpleType" )
)
);
Is this possible with Jackson/ObjectMapper?
What settings and annotations would I need?
If your Item class has a string constructor, it will be called with the "simpleType" value.
class Item {
private String name;
private String functionName;
public Item() {
}
public Item(String name) {
this.name = name;
}
// getters and setters here
}
Full demo
public class Request {
public static void main(String[] args) throws IOException {
String json = "{\"subItems\":[" +
"{\"name\":\"complexType\",\"functionName\":\"SomeFunction\"}," +
"\"simpleType\"" +
"]}";
Request request = new ObjectMapper().readValue(json, Request.class);
System.out.println(request);
}
private List<Item> subItems;
public Request() {
}
public Request(Item... subItems) {
this.subItems = Arrays.asList(subItems);
}
public List<Item> getSubItems() {
return this.subItems;
}
public void setSubItems(List<Item> subItems) {
this.subItems = subItems;
}
#Override
public String toString() {
return "Request [subItems=" + this.subItems + "]";
}
}
class Item {
private String name;
private String functionName;
public Item() {
}
public Item(String name) {
this.name = name;
}
public Item(String name, String functionName) {
this.name = name;
this.functionName = functionName;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getFunctionName() {
return this.functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
#Override
public String toString() {
return "Item [name=" + this.name + ", functionName=" + this.functionName + "]";
}
}
Output
Request [subItems=[Item [name=complexType, functionName=SomeFunction], Item [name=simpleType, functionName=null]]]
This is my object :
public class ObjectsInGroupRealm extends RealmObject {
#PrimaryKey
private Long id;
private String name;
private String groupName;
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 String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
And when I create a new object I want to check if object is exist this same name and this same groupName . A object name could be in few groups. This is my code how I save a objects :
public static void saveObjectsInGroup(ArrayList<String> objects, String groupName , Realm realm){
for(String object : objects){
ObjectsInGroupRealm objectsInGroupRealm = new ObjectsInGroupRealm();
Long key;
try {
key = (Long) realm.where(ObjectsInGroupRealm.class).max("id") + 1;
} catch (NullPointerException ex) {
key = 0L; // when there is no object in the database yet
}
objectsInGroupRealm.setId(key);
objectsInGroupRealm.setName(object);
objectsInGroupRealm.setGroupName(groupName);
realm.beginTransaction();
realm.copyToRealm(objectsInGroupRealm);
realm.commitTransaction();
}
}
So the easiest way is doing a query and checking if the returned Object is null:
ObjectsInGroupRealm object = realm.where(ObjectsInGroupRealm.class)
.equalTo("name", name)
.equalTo("groupName", groupName)
.findFirst();
if(object == null){
//add new object
} else {
//handle object already existing
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
[UML Diagram][1]
I'm studying for the midterm exam next week and I'm practicing some given examples from my professor; however, I am having some trouble with class return type methods.
I attached UML diagram just in case.
What i'm trying to understand is getPerson method in Job class. I don't think i need a array list in Job class to store all the employee. Because I have an array list already in Company class. Also return type is Employee class that I'm not sure how to get person's info using this class return type.
My problems
public Employee getPerson() {} in Job class
public boolean isVacant() {} in Job class
Also would you mind checking getVacantJobs, getFilledJobs, and getAllJobs methods if those are correctly built?
I used iterator to display all the stored jobs.
---------------------------Employee Class -----------------------------
public class Employee {
private String name;
private int id;
public Employee(int id, String name) {
this.name = name;
this.id =id;
}
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public final int getId() {
return id;
}
public final void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + "]";
}
}
----------------------------Job Class--------------------------------------
public class Job {
private String description;
private int id;
private double maxSalary;
public Job(int id, double maxSalary, String description) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
public Job(int id, double maxSalary, String description, Employee e1) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
#Override
public String toString() {
return "Job [description=" + description + ", id=" + id
+ ", maxSalary=" + maxSalary + "]";
}
public final String getDescription() {
return description;
}
public final void setDescription(String description) {
this.description = description;
}
public final double getMaxSalary() {
return maxSalary;
}
public final void setMaxSalary(double maxSalary) {
this.maxSalary = maxSalary;
}
public final int getId() {
return id;
}
public Employee getPerson() {
retrun
}
public final void setPerson(Employee person) {
this.id = person.getId();
}
}
--------------------------Company Class ---------------------------
import java.util.ArrayList;
import java.util.Iterator;
public class Company {
static ArrayList list = new ArrayList();
Iterator itr = list.iterator();
private String name;
public Company(String name) {
this.name = name;
}
public Company() {
// TODO Auto-generated constructor stub
}
public static void addJob(Job j1) {
list.add(j1);
}
public void removeJob(int id) {
list.remove(id);
}
public ArrayList<Job> getVacantJobs() {
while (itr.hasNext()) {
if ((itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getFilledJobs() {
while (itr.hasNext()) {
if (!(itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getAllJobs() {
while (itr.hasNext()) {
System.out.println(itr.next());
}
return null;
}
}
Add field person to Job class.
public class Job {
// .....
private Employee person;
public Employee getPerson() {
return person;
}
public final void setPerson(Employee person) {
this.person = person;
}
public boolean isVacant() {
return person == null;
}
}
And add jobs field to Company class.
public class Company {
// static ArrayList list = new ArrayList(); // You don't need this
// Iterator itr = list.iterator(); // You don't need this.
// .....
private ArrayList<Job> jobs = new ArrayList<>();
public ArrayList<Job> getVacantJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getFilledJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (!job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getAllJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
result.add(job);
return result;
}
}
I have a Class Foo that has a Constructor that sets name and id.
In another Class I have a List<String> of messages where I can extract the name and id.
I'm able to successfully set the Constructor by looping through the list using regular foreach loop. How do I achieve this using Stream Java 8 or Lambda or Method References
public class ConstructorTest {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
List<String> userList = new ArrayList<String>();
userList.add("username1_id1");
userList.add("username2_id2");
//I want to replace the below foreach loop with stream/lambda/methodreferences
for (String user : userList) {
Foo foo = new Foo(getName(user), getId(user));
fooList.add(foo);
}
}
private static String getName(String user) {
return user.split("_")[0];
}
private static String getId(String user) {
return user.split("_")[1];
}
}
Foo Class:
public class Foo {
public Foo(String name, String id) {
this.name = name;
this.id = id;
}
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
How about this?
userList.stream().map(user -> new Foo(getName(user), getId(user)).forEach(userList::add)
Or this
userList.forEach(user -> userList.add(new Foo(getName(user), getId(user))))
I have a method which returns the list like
public List<Object> getSomeData(SomeBean sb) {
List<Object> data = Lists.newArrayList();
data.add(sb.getId()); // Id->long
data.add(sb.getName()); // name->String
.....
return data;
}
and Now I have to iterate over this list, which I have to check type every time as
for (int i = 0; i < data.size(); i++) {
if (data.get(i) instanceof String) {
//append
}
if (data.get(i) instanceof Long) {
//append
}
....
}
I need to append the elements of list in the loop.
Are their any better way to achieve this, may be without using instanceof operator.
You should create a class for that data and return an instance of it instead of a List.
class SomeEntity {
long id;
String name;
public SomeEntity(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
#Overrides
public String toString() {
return id + " " + name;
}
}
Just use it in your code:
public SomeEntity getSomeData(SomeBean sb) {
SomeEntity entity = new SomeEntity(sb.getId(), sb.getName());
return entity;
}
Edit: you can override the toString() method of the class and use it in your code (added above)
Here you go:
final List<Object> someData = new ArrayList<>();
someData.add("stringValue"); //String
someData.add(1L); //Long Value
final String result = someData.stream()
.map(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println(result);