i'm trying to do a configurations file from an array of objects, where the properties are taken from a range of getters.
eg
prop.setProperty("Name", bugs[0].getName());
prop.setProperty("Species", bugs[0].getSpecies());
When i try, for example
prop.setProperty("Energy", bugs[0].getEnergy());
it says
The method setProperty(String, String) in the type Properties is not
applicable for the arguments (String, int)
How would I do method of setProperty(String, Int)?
EDIT*
Also, How do i write for an array of the objects, looping bugs[i] doesn't seem to work either.
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name", bugs[i].getName());
prop.setProperty("Species", bugs[i].getSpecies());
prop.setProperty("X", String.valueOf(bugs[i].getX()));
prop.setProperty("Y", String.valueOf(bugs[i].getY()));
prop.setProperty("Energy", String.valueOf(bugs[i].getEnergy()));
prop.setProperty("Symbol", String.valueOf(bugs[i].getId()));
}
// save properties to project root folder
prop.store(output, null);
How would i make it show the values for all the bugs, its only showing the last one?
bugs[0].getEnergy() is giving integer value to you and you are setting integer value insted of string that why exception came in your code.
Try
prop.setProperty("Energy", String.valueOf(bugs[0].getEnergy()));
For second part of Question :
How do i write for an array of the objects, looping bugs[i] doesn't
seem to work either.
Your loop showing last value because your key of property is same, you are not changing the key assigning all values to same key so it is giving you last value.
Try something , It will create new keys
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name"+i, bugs[i].getName());
prop.setProperty("Species"+i, bugs[i].getSpecies());
}
Mainly you can do this in two ways:
First way:
Overloading the setProperty(); metod. As it seems you decleared this method some where like this:
public void setProperty(String s1, String s2) {
// Doing some operations
}
Now, you can overload another method with the same name, but different signature to handle another kind of arguments (String - int), like this:
public void setProperty(String s1, int value) {
// Doing some operations suitable for this kind of method
}
Second way:
You can also easily convert the value of given integer to the string, by String.valueOf(); method, like this:
prop.setProperty("Energy", String.valueOf(bugs[0].getEnergy()));
EDITED:
In the loop you entered here, you're overwriting the values of prop object properties every time you loop through for.
First time the name of prop will be the bugs[0].getName(). In the next time, the last value will be deleted and bugs[1].getName() replaces it.
So if you want to store all of bugs array properties, you need an array of prop like objects (I don't know whats the type of prop but I assume it's Prop). So you need to write something like this:
Prop[] props = new Prop[bugs.length];
And then set properties of it's elements.
Also if you want to store all of properties in one object, you have to change the given key to setProperty(String, Int) method (as the String). So you can do something like this:
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name " + i, bugs[i].getName());
prop.setProperty("Species " + i, bugs[i].getSpecies());
// An so
}
prop.store(output, null);
Related
Its not duplicated i have read all and nothing suite in my case so please read it and answer it.I have two arrays.One is Vehicle and the other is pin.This is a part of code and it is only the method.
First question :
if i have declare the arrays on the same main out of
this method the way i pass them on the method is right?With other words the parameteres
are good or need (int vehicle[],int pin[]) or something else?
Second question +=
i dont know what it does but i think that in the array pin it takes
as an ecample the pin[1] cost has 10.The number 10 is taken by
getcostosvehicle();(we put it from userinput) so when the array fills
and it hasnt any slot then the costs will be finished.As a result will
have lets say the ended slot is 20 in pin[20] lets say it has 350.The
return statement will give us only the last cost?It would be better to
write return pin[i]; so in that way it will return all the pin with
the whole costs of each one slot,am i right?
Third question
On this code and that i want to write me as an answer could you return
two arrays?I mean return pin[i],vehicle[i]; not only return pin[i];.If
yes,could you do an answer and doesnt need to fill in the vehicle
array.Just to show me if this can happen.
public static int getallcosts(vehicle[],pin[]) {
int costos = 0;
for(int i =0; i < pin.length; i++) {
costos += pin[i].getcostosvehicle();
}
return costos;
}
if i have declare the arrays on the same main out of this method the way i pass them on the method is right?With other words the parameteres are good or need (int vehicle[],int pin[]) or something else?
I'm not sure I understand you correctly but of course getallcosts(vehicle[],pin[]) won't compile, i.e. you need to define the type of the arrays (or the names if vehicle and pin would actually be the types).
It would be better to write return pin[i]; so in that way it will return all the pin with the whole costs of each one slot,am i right?
No, you can only have one return value. If you want to return multiple values then you need to wrap them in an object (array, list, pojo, etc.).
On this code and that i want to write me as an answer could you return two arrays?
See the part above: if you want to return multiple arrays you need to add them so some object and return that object. Since you didn't provide the types for the arrays I'll use another example:
class Result {
String[] strings;
int[] numbers;
}
Result someMethod() {
Result r = new Result();
r.strings = new String[]{"a","b","c"};
r.numbers= new int[]{1,2,3};
return r;
}
First question:
If you are calling a method (so you're not defining it) yuo can write parameters as you do, without type.
Otherwise you need to specify type. In this case you are defining a new method so you need to specify type of parameters.
Second question:
'+=' it's like write
costos = costos + pin[i].getcostosvehicle();
So you will add to the current value of 'costos' the 'costos' of vehicle retrieved by 'getcostosvehicle()';
Third question:
As i know you can't return two Objects of any type in return statement.
So you'll need to reorganize your code to do operation first on an array and return it and then on the other one and return it.
For example you can do a method that have as parameter a generica array do some logic inside and then return it. You will call this method for the first array and then for the second.
Example:
public int[] method(int[] array){
/*do something
*/
return array;
}
Then you will call:
firstArray = method(firstArray);
secondArray = method(secondArray);
If you want more, or i have to change something comment please.
I am wondering if there is a way to use compareTo() without having to iterate through each string element in the data set, I'm pretty sure this is not possible using arrays, but is there a data structure that is capable of working in that way?
See example below for clearer explanation:
public static int PronounDetector(String [] pronouns)
{
String [] you = {"you", "You"};
for (int i = 0; i < pronouns.length; i++)
{
if (pronouns[i].compareTo(you) == 0)
//Is there a way for compareTo to run through
//the entire String data set without having to make
//it iterate through each element using a for loop?
{
return 2;
}
}
}
EDIT: I understand that no matter what the program will iterate through the data set, (how else will it find a match?), I am just looking to see if there is a way to do it without me actually having the physically type in the for loop.
The must be meet two conditions if you want to skip some data during search processing.
The data must be related.
The data must be organized.
You can improve your search, by sorting the array and then compare from the middle.
Then in each step you will reduce element that must be compare by half.
Instead of array you can used TreeMap, that will store the data in tree structure to have same result.
Code example:
public static boolean contains(String[] array, String key) {
Objects.requireNonNull(array,"The array must not be null");
Objects.requireNonNull(array,"The key must not be null");
String[] copy = array.clone();
Arrays.sort(copy);
return Arrays.binarySearch(copy, key) != -1;
}
Yes, you don't have to "double iterate" (even though that's exactly what happens under the hood) you can convert the array you to a string and search it using contains():
String youStr = Arrays.deepToString(you);
System.out.println(youStr.contains(pronouns[0])); // prints 'true'
I would like to have an arrayList that holds reference to object inside the reduce function.
#Override
public void reduce( final Text pKey,
final Iterable<BSONWritable> pValues,
final Context pContext )
throws IOException, InterruptedException{
final ArrayList<BSONWritable> bsonObjects = new ArrayList<BSONWritable>();
for ( final BSONWritable value : pValues ){
bsonObjects.add(value);
//do some calculations.
}
for ( final BSONWritable value : bsonObjects ){
//do something else.
}
}
The problem is that the bsonObjects.size() returns the correct number of elements but all the elements of the list are equal to the last inserted element.
e.g. if the
{id:1}
{id:2}
{id:3}
elements are to be inserted the bsonObjects will hold 3 items but all of them will be {id:3}.
Is there a problem with this approach? any idea why this happens?
I have tried to change the List to a Map but then only one element was added to the map.
Also I have tried to change the declaration of the bsonObject to global but the same behavior happes.
This is documented behavior. The reason is that the pValues Iterator re-uses the BSONWritable instance and when it's value changes in the loop all references in bsonObjects ArrayList are updated as well. You're storing a reference when you call add() on bsonObjects. This approach allows Hadoop to save memory.
You should instantiate a new BSONWritable variable in that first loop that equals the variable value (deep copy). Then add the new variable into bsonObjects.
Try this:
for ( final BSONWritable value : pValues ){
BSONWritable v = value;
bsonObjects.add(v);
//do some calculations.
}
for ( final BSONWritable value : bsonObjects ){
//do something else.
}
Then you will be able to iterate through bsonObjects in the second loop and retrieve each distinct value.
However, you should also be careful -- if you make a deep copy all the values for the key in this reducer will need to fit in memory.
ArrayList<yellowPage> ob1 = new ArrayList<yellowPage>();
yellowPage thing = new yellowPage(100,100);
thing.calc(i,y,s3);
ob1.add(thing);
I stored some data in thing. How can I retrieve the value stored in ob1.thing?
If you know the index, you can do yellowPage
yellowPage yp = ob1.get(index);
Otherwise you need to iterate over the list.
Iterator<yellowPate> iter = ob1.iterator();
while(iter.hasNext())
{
yellowPage yp = iter.next();
yp.whateverYouwantGet();
}
Note: I just typed code here, there may be syntax errors.
int x=5;
int info=ob1.get(x).getInfo();
The above example will get whatever information you wanted from your yellow pages class (by using a getter method) at the 6th index (because 0 counts) of your array list ob1. This example assumes you want an integer from the yellow page. You will have to create a getter method and change the x to the index of the yellow page you want to retrieve information from.
An example getter method (which you should put in your yellow pages class) could look like this:
public int getInfo() { return z; }
In the above case z may be an instance variable in your yellow pages class, containing the information you're looking for. You will most probably have to change this to suit your own situation.
If you wanted to get information from all yellow pages stored in the array list then you will need to iterate through it as Chrandra Sekhar suggested
Use an Iterator object to do this.
ArrayList<yellowPage> ob1 = new ArrayList<yellowPage>();
yellowPage thing = new yellowPage(100,100);
thing.calc(i,y,s3);
ob1.add(thing);
yelloPage retrievedThing = null;
Iterator<yelloPage> i = ob1.iterator();
if(i.hasNext()){
retrievedThing = i.next();
}
You could have the data stored in thing (horribly named variable) simply returned from the calc method. That way you don't need to maintain state for prior calculations in subsequent calls. Otherwise you just need a getter type method on the YellowPage class.
public class YellowPage {
private int result;
public void calc(...) {
result = ...
}
public int getResult() {
return result;
}
}
Print the list and override toString method.
public String toString()
{
return (""+ a+b); //Here a and b are int fields declared in class
}
System.out.print(ob1);
Class ArrayList<E>
Syntax
ArrayList<Integer> list = new ArrayList<Integer>();
You replace "Integer" with the class that the list is of.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
E represents an Element, which could be any class.
ensureCapacity is used to ensure that the list has enough capacity to take in the new elements. It's called internally every time you add a new item to the list. As the name suggests, ArrayList uses an Array to store the items. So when the array is initialized, it's given an arbitrary length, say 10. Now once you've added 10 items, if you go to add the 11th item, it'll crash because it exceeds the arrays capacity. Hence, ensureCapacity is called (internally) to ensure that there's enough space. So if you were adding the 11th element, the array size might be, say, doubled, to 20.
Alright, I am not completely sure that I worded the title right, but I want to use an int variable to define another int to go through a method. In other words, I want to be able to have the int/name/thingy variable go through a ++ statement, and then the next variable would go through the method. Is this possible?
An int array might solve your problem. The array stores your ints ("variables"), another one runs throught the index (your ++ operation):
int[] values = loadValuesInArray(); // some magic to get the populated array
for (int i = 0; i < values.length; i++) {
myMagicMethod(values[i]); // calling the method with int values
}
If you need named variables, then you can use a map:
Map<String, Integer> variables = new HashMap<String, Integer>();
variables.put("a", 1);
variables.put("b", -10);
variables.put("c", 25);
myMagicMethod(variables.get("b")); // calls method with value from "variable" b
You can use reflection.
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
http://www.java2s.com/Tutorial/Java/0125__Reflection/Catalog0125__Reflection.htm
or see to have an idea.
Setting variables by name in Java
You almost certainly want to be using something like a Map or List (essentially a dense map with a small positive int key).
If you don't need to create a new variable with a name, stored in another variable, then reflection is a way to go.
String varName = "x";
Point2D point = new Point(15, 2);
Integer val = (Integer)Point.class.getDeclaredField(varName).get(point);
assert val == 15;
You say "I want to use an int variable to define another int" do you mean something like
int a = 0; //declare a new variable a of type int and assign it to zero
a b = 0; //declare a new variable b of type a which is an int and assign it to zero
From what you said, that is what it appears you are saying. If that is the case, I do not think you can do that. My memory says that there is a method that allows you to determine the type of an object, but to use that as a declaration of another variable... I don't know if you can do that.