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 9 years ago.
Improve this question
Are there any alternatives to? (1 group )
class team {
List<String> team = new ArrayList<String>
int score = 0;
}
Is there an object that that store a List or Set 'String', that can hold a value of a Integer?
Thanks in advance.
It sounds like you need a Score object:
class Score
{
int points;
String groupName;
}
and then a List<Score> of them
What you probably want is a new type that holds both the String and the int that you care about, e.g.:
public class Score {
String group;
int score;
}
...
List<Score> scores = new ArrayList<Score>();
To answer your original question, though: The narrowest common type between String and Integer is Object, and you can construct such a List:
List<Object> group = new ArrayList<Object>();
group.add("string");
group.add(1);
Of course, this isn't restrictive to just String and Integer types, you can add any type of object.
Alternatively, you could coerce your Integer into a String:
String someNumber = String.valueOf(1);
Or construct a new class that is more restrictive, and acts as a kind of union:
public class StringOrInteger {
private final Object value;
public StringOrInteger(String string) {
value = string;
}
public StringOrInteger(Integer integer) {
value = integer;
}
public Object getValue() {
return value;
}
}
...and then have a list of these:
List<StringOrInteger> group = new ArrayList<StringOrInteger>();
(which will be at least compile-time restrictive)
You could get fancier with the class, and make it so that it returns a correctly cast object, but I suppose it depends on your use-case where you want to go with this.
Related
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 2 years ago.
Improve this question
I'm trying to create a method in java which compares some products. I need to compare them by unit of measure and then by quantity, but I don't know how. I need to use object.equals ?
I'll put my code here.
public abstract class Produs implements Comparable {
private String tipProdus;
private String unitateMasura;
private int cantitate;
public Produs(String tipProdus, String unitateMasura, int cantitate) {
super();
this.tipProdus = tipProdus;
this.unitateMasura = unitateMasura;
this.cantitate = cantitate;
}
public Object genereazaDescriere() {
Object String = null;
return String;
}
public void compareTo() {
tipProdus.equals(unitateMasura);{
}
}
}
First of all, you can not create objects from an abstract class so you need to change that or just forget about that constructor because you won't be able to use it.
To compare two objects you need to create a comparator class so you would be able to compare objects according to the attributte you want to.
So in this case you need to create two comparators, one to compare them by unit of measure and another to compare it by quantity.
So it would be something like this:
Comparator by unit of measure:
public class UnitOfMeasureProdusComparator implements Comparator<Produs> {
#Override
public int compare(Produs p1, Produs p2) {
return p1.getUnitateMasura().compareTo(p2.getUnitateMasura());
}
Comparator by quantity:
public class QuantityProdusComparator implements Comparator<Produs> {
#Override
public int compare(Produs p1, Produs p2) {
return p1.getCantitate().compareTo(p2.getCantitate());
}
So now for example if you have an arraylist of Produs objects you can compare them like this:
ArrayList<Produs> products = new ArrayList<>();
Produs p1 = new Produs("x", "centimeters", 5);
Produs p2 = new Produs("y", "meters", 4);
products.add(p1,p2);
//now you have two objects created so if you want to sort them by there quantity u can do it like this:
Collections.sort(productos, new QuantityProdusComparator());
It will sort the list according to the comparator you use.
Internally the comparator class will send a 0 if the objects are equal, a -1 if the object is smaller than or a 1 if the object is bigger than.
If you comparing string attributes it will do it in alphabetical order.
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 8 years ago.
Improve this question
Is there an array that I can reference the fields of an object from?
The objects fields are of type String, String, String and int. Is it possible to reference these through an array?
Do you mean that you have something like this?
public class SomeThing
{
public String thing = "something";
public String thing2 = "somethingElse";
public String thing3 = "anotherThing";
public int id = 42;
}
And you want to access those as an array?
If so, you can do this reflectively, like so:
SomeThing instance = new SomeThing();
Field[] fields = instance.getClass().getFields();
Object[] array = new Object[fields.length]
for(int i = 0; i < fields.length; i++)
{
fields[i].setAccessible(true);
array[i] = fields[i].get(instance);
}
You can reference an object in an array with the [] operator. From there on, it's just a normal reference. E.g.:
myObjectArray[4].getSomePropertyOfMyObject();
What do you mean? Can you explain it better.
You can have an Array of objects in Java.
If for example your object is called Animal you can create an array of Animals like this:
Animal[] animals= new Animal[sizeOfAnimals];
Is it what you want? Just substitute Animal with your object.
Cat [] list = new Cat[10];
So once you have a list and objects of a type inside the list then you can call them like you would any other object.
list[0].methodName();
Notice list[0] behaves like a Cat object, because that is what it holds.
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 8 years ago.
Improve this question
public class abc<E>{
Arraylist<E> returnthis = new Arraylist();
public abc<E> fuction(E c)
{
returnthis.add(c);
return returnthis
}
}
// main
abc array = new array();
temp = array.add(4);
How can i return an arraylist from a function which return object of a class.
If I understand your question, then you will need to add an accessor (or getter) method to your abc class -
List<E> returnthis = new ArrayList<>(); // <-- note caps and diamond operator.
public List<E> getList() {
return returnthis;
}
Then you can
abc<Foo> array = new abc<>(); // <-- abc is generic
List<Foo> foos = array.getList(); // <-- like so
Finally, abc is a very poor class name. It's nondescript and doesn't follow Java capitalization conventions.
Your code is hard to read. It might be why you're having trouble understanding it.
You've got to make the return type match the variable you're returning.
public class Demo<E> {
List<E> data = new ArrayList<E>();
public List<E> addToData(E c) {
data.add(c);
return Collections.unmodifiableList(data);
}
public String toString() { return this.data.toString(); }
}
First of all you don't seem to have the basics down of arrays quite yet as bits of that isn't right. First you need to understand returning an array object correctly. Here is an example:
ArrayList<E> myArray = new ArrayList<E>();
public ArrayList<E> getMyArray(){
return myArray;
}
Secondly capitalize the class name my OCD is going crazy right now.
Now look at your array, it doesn't hold values of the class you just created if thats what your trying to do. I am not entirely sure what it is your trying to do yet though you need to fix up your code first.
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 9 years ago.
Improve this question
Please don't chalk this up as a dumb question. This may seem very obvious to some, but it is not to me.
I am working on a very, very large codebase.
I continually see, in numerous classes, this pattern:
public class myClass {
public myClass[] doGetMyClassList(final String someParam) {
// some code
}
}
The class contains a method that returns an array or a list of itself.
Is there a name for this? I would like to know if this belongs to some kind of programming practice.
The type signature alone doesn't tell you what pattern it is, you also need to know what it collaborates with and how it's used.
It seems like it might be attempting to do the repository pattern, in which a repository class fetches collections of some other class according to parameters passed in. However, you would typically make the repository a separate class from the class it is fetching for you. It's kind of hard to switch out to another repository for testing or other reasons when the class just returns it's own type.
Though I could not find an explicit design pattern or a well defined interface. I find a parallel here
listFiles() method of java.io.File which returns an array of File objects if its a directory.
Also any other usecase where objects of same class are related could be a parallel. ex: Person class with friends method which returns an array of Person objects.
Generics as a programming construct is a great tool to express these relations(i.e. methods). Self-bound Generics are feasible and are often seen in many places ex:
import java.util.Arrays;
public class Grade < T extends Grade >{
private static final int MAX = 5 ;
private int grade;
public Grade(int grade) {
this.grade = grade;
}
public T[] getGradesBelow() {
Grade[] lower = new Grade[this.grade];
for (int i = 0; i < this.grade; i++) {
lower[i] = new Grade(i);
}
return (T[]) lower;
}
public String toString(){
return grade + "";
}
public static void main(String[] args){
Grade grade = new Grade(Grade.MAX);
System.out.println(Arrays.toString(grade.getGradesBelow()));
}
}
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 9 years ago.
Improve this question
The problem should be on the createClass() method... is it wrong to use classes.add(this)?
private static ArrayList<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
public void setVirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
public void createClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
classes.add(this);
}
More details on the problem: Failed to store values in ArrayList of class object. (CODE EDITED)
I suppose you want to keep a record of all created classes?
It is generally bad practice to pass out this in a constructor because, by definition, this hasn't been constructed yet. In this instance I don't think it will cause problems but it certainly doesn't smell right.
I would consider using a static factory method or another form of factory pattern so that you can split up object creation and the storing of instances.
No one can tell you whether it is right or wrong unless you tell what you are trying to do.
If what you are doing is something like : (assume your class is called Foo)
Foo foo = new Foo();
foo.createClass("Blablabla", "method1", true);
foo.createClass("AnotherClass", "method2", true);
something like that, then yes, you are probably wrong. Because what you are doing is simply changing the only Foo instance with different attribute, and adding the same object to the list.