This question already has answers here:
Resize an Array while keeping current elements in Java?
(12 answers)
Closed 9 years ago.
I'd like to know if I can re-dimension an array as long as I want. I tried to do it and it seems there aren't any problems. I created an array with these steps
//step 1
String parole[];
//step 1
parole = new String[1];
parole[0] = "ciao";
//step 1
parole = new String[2];
parole[1] = "buongiorno";
I ask this beacuse there something in my mind that tells me that i can't do it. Maybe i read something somewhere someplace...
Of course you can create a new array object and assign it to an array reference.
But if you expected that parole[0] would still have "ciao" in it after your last step, you're wrong.
Yes you can, but you need to copy the first array into a new one.
Check this sample code:
public class ArrayCp {
public static void main(String[] args)
{
String[] primoArray = new String[1];
primoArray[0] = "Ciao";
// Copio il primo array nel secondo cambiandone la dimensione (secondo parametro)
String [] secondoArray = Arrays.copyOf(primoArray, 2);
secondoArray[1] = "Buona Sera";
for(String s : secondoArray) {
System.out.println("Elemento: " + s );
}
}
}
However is better going with an ArrayList:
ArrayList<String> theArr = new ArrayList<String>();
theArr.add("Ciao");
theArr.add("Buona Sera");
theArr.add("Buona Notte");
and get back to a simple array with
String [] resArray = theArr.toArray(new String[theArr.size()]);
Making a "new String[]" is just that, making a NEW string array. This means that any data you previously had in the reference is overwritten by the "new" object. (If you had other references to the string[] it wouldn't be lost however)
So, in short, no, you cannot "re-dimension" an array.
In your case, it is probably best to use an ArrayList, which provides for dynamic resizing (and is much easier to work with).
I agree with #BigMike
You should try ArrayList because it has built in methods for capacity which is far better than we doing it manually.
It does the work in amortized time which will be hard for us to achieve.
Refer this for more details.
Related
I've been trying to implement a Set data structure with key, value.
I have a txt file (EOL) have a String, line number something like this:
Adam,1
Mary,2
Michael,3
My goal is store this key-value inside a Set.
Here is my code:
public class Main {
public static void main(String[] args)throws Exception
{
Scanner scanner = new Scanner(new FileReader("C:\\Users\\musti\\Desktop\\demo.txt"));
HashMap<String,Integer> mapFirstfile = new HashMap<String,Integer>();
while (scanner.hasNextLine()) {
String[] columns = scanner.nextLine().split(",");
mapFirstfile.put(columns[0],Integer.parseInt(columns[1])); }
// HashMap sıralı yazdırmaz, LinkedHashSet sıralı tutar, ama ekstradan linkedlist lazım.
System.out.println(mapFirstfile);
System.out.println(mapFirstfile.keySet());
System.out.println(mapFirstfile.values());
Set<HashMap> setFirstfile = new HashSet<HashMap>();
}
This is not an answer actually, but too long for comment...
First of all, Set is a structure of unique (in regards to equals()) values.
So your code above actually uses the correct structure Map where you map String to a number (Integer).
Question 1
Is the number needed, is it in the file? You can calculate it from input
Adam
Mary
Michael
we know, that Adam is on a first line...
edit 1: You can use counter which you will increment every time you enter the loop. There is nothing in Java API to do that for you...
Question 2
In your question, I'm missing information about what is not working... What is your expectation that is not true?
Question 3
What in case of duplicates?
Alfa
Bravo
Alfa
Is it ok, that on the 3rd line you remap Alfa to 3?
Question 4
What is your motivation to use Set?
As I wrote in Set contains "single" items. If your item contains several fields, you can wrap in in an Object, but I do not see the benefit...
Something like
class Item {
String line;
int lineNumber;
// TODO: 1 add constructors
// TODO: 2 add getter & setters
// TODO: 3 implement equals() and hashCode()
}
and add it to Set like this:
Set mySet = ...
mySet.add(new Item(line, counter)); // you need to add such constructor
I have a homework to do in java about ArrayList and Generics types.
I have 2 classes :
-> CoupeDeA
-> TableauPartiel
CoupeDeA is just a describer from where to where an array is cut.
(It contains only two private integer variables "begin" and "end")
TableauPartiel is the class where the ArrayList is.
My problem is I need to create a method in TableauPartiel like this :
public TableauPartiel<E> coupe(CoupeDeA coupe)
And the TableauPartiel returned needs to be a reference of my intial TableauPartiel. Example :
Integer[] arr = {8,7,6,5};
TableauPartiel<E> tab = new TableauPartiel<>(arr);
TableauPartiel<E> tab2 = tab.coupe(1,3);
tab2.set(1,45);
This code is supposed to set 45 at index 1 of my tab2 and at the same time set 45 at index 2.
But I tried many different ways and I managed to get the sublist, but it is not pointing to my original ArrayList.
For example, I tried something like this :
private ArrayList<E> tableau;
...
public TableauPartiel<E> coupe(Coupe coupe)
throws IndexOutOfBoundsException {
if (coupe.getBegin() >= 0 && coupe.getEnd() <= tableau.size()) {
TableauPartiel<E> tab = new TableauPartiel<>((E[]) new Object[coupe.getEnd()-coupe.getBegin()]);
for (int i = 0; i < coupe.getEnd()-coupe.getBegin(); ++i) {
tab.set(i, this.get(coupe.getBegin()+i));
}
return tab;
} else {
throw new IndexOutOfBoundsException();
}
}
How can I do to get a sublist which refers to his original ArrayList?
I've found a solution for my code with the subList method and by switching the signature of my ArrayList to List but my teacher doesn't want us to use subList finally.
Here is my code with the subList method :
TableauPartiel<E> tab;
if (coupe.getDebut() >= 0 && coupe.getFin() <= taille()) {
if (coupe.getFin() == -1)
tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),taille()));
else
tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),coupe.getFin()));
return tab;
} else {
throw new IndexOutOfBoundsException();
}
}
Few small things first:
stick to English words in your code. Especially in names of classes, functions, variables, etc - names have to reveal intentions (without Google Translate). Best not to obtain a bad habit by letting yourself do otherwise.
I am not so sure how your Coupe is expected to work (is 0 a legal min number or 1?) but coupe.getEnd() <= tableau.size() might get out of hand
Now my suggestion for the solution:
I suggest you modify your TableauPartiel class to have start and end integer fields in addition to private ArrayList<E> tableau; reference you already have. Maybe add a new 'copy constructor' accepting an instance of
TableauPartiel (from which you can copy reference to tableau) and two int values indicating which part of the original tableau you can use (trick here is to also look at start and end values of the object you're 'sublisting' from). That way, when you're calling #coupe you can check for validity of the input numbers (as you already do) and simply return a new TableauPartiel object with a reference to this and method params - start and end values. Add some indexes manipulation logic using those start and end to whatever methods your TableauPartiel has and you should be good to go.
Hello guys I am trying to write an array list of strings with not specified size, I am setting a for loop with a sentinel to control the amount of input, but it seems not to work, this is the piece of cod that has the problem I think, Pleasse help !
public static void main(String args[])
{
ArrayList<String> a=new ArrayList<String>();
String string;
String string2;
char[] string1=new char[1];
char c;
for(int i=0;!"null".equals(a.get(i));i++)
{
string=input.nextLine();
a.add(i,string);
}
I assume you are getting an error. I suggest you read the error and if you don't understand it, you should search for it or include it in the question.
In this case, your test is broken. You don't have either a null value or "null" (which is not the same thing) in fact you don't have an element 0 which is why it is throwing an exception.
A simple solution is to check what you reading as you read it.
List<String> a = new ArrayList<String>();
while(input.hasNext())
a.add(input.readLine());
!"null".equals(a.get(i)) will just check if the string returned by a.get(i) does not equal "null". I think what you wanna do is check a.get(i) == null, which will not work since requesting an item from a List that is at an index that is bigger than the list's size will throw a java.lang.IndexOutOfBoundsException.
To properly iterate over a List, use a foreach loop:
for(Object o : list) {
//Execute your code
}
I think the part where I have to get a false value by !"null".equals(a.get(i)) is not working like it should because the program does not get out of the loop
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a situation that I need to fill an object array.
This is my code:
final class ObjectClass
{
List<ObjectClass> array;
private int data;
ObjectClass(int data)
{
this.data = data;
}
public void fillArray() {
array = new LinkedList<>();
for(int i = 0;i < array.size();i++)
{
data++;
array.add(new ObjectClass(data));
}
}
}
And i am getting no result with this. What is wrong with that?
Is it valid to add like this: array.add(new ObjectClass(data)) ?
There is no point about results and logic in this situation. I just want to make the ObjectClass's array with different data values. I saw, someone used a reference variable and stored it in an array, but is it valid to make it without it by creating only object?
Add a print method:
public void display() {
for(ObjectClass e : array) {
System.out.println(e);
}
}
The reason why nothing is happening is here:
for(int i = 0;i < array.size();i++)
The line before, you just created the array so it's still empty - therefore, the body of the loop isn't executed at all.
Every time you call fillArray, you are destroying the data (however it made its way in there) in the array with this:
array = new LinkedList<>();
First, change your field to use eager initialization instead, so you're not overwriting your field on every method call.
List<ObjectClass> array = new LinkedList<>();
Now, for your method. You don't enter the loop since array is always empty. Depending on what you're trying to accomplish, you should pass the object through, or create a copy of it n times.
public void fillArray(int times) {
for(int i = 0;i < times; i++) {
data++;
array.add(new ObjectClass(data));
}
}
Lastly, observe that, if the loop did work, data and array.size() would be equivalent (so long as you didn't remove anything). I'd rethink the purpose/intent of that variable.
Declare the List<ObjectClass> array as static, it will do what you are trying to achieve by creating a Class variable not at Object Level
The problem is the array (which is not actually an array by the way - it's mis-named) initially has size 0, so the method does nothing.
You have forgotten to consider how many numbers you want to "fill" the data structure with.
Does anybody know if there is any easy way within Java to prefix one string onto multiple other strings?
For example, if I have the following snippet of Java code ;
String includeDir = "/usr/local/boost-1.52.0/include";
ArrayList<String> filenamesRelative = new ArrayList<String>(),
filenamesAbsolute = new ArrayList<String>();
filenamesRelative.add("/boost/aligned_storage.hpp");
filenamesRelative.add("/boost/any.hpp");
I would like to be able to prefix the value of the variable 'includeDir', i.e. "/usr/local/boost-1.52.0/include", onto the front of each value in the ArrayList filenamesRelative.
Ideally, I would like to be able to do something like the following ;
filenameAbsolute = filenamesRelative.prefixAll(includeDir);
I don't necessarily have to use ArrayLists in the solution; I have just used them above for illustrative purposes.
From memory, you can do something like this rather easily in C++ using the STL, however my current working knowledge of Java isn't all that good unfortunately :(
Thanks in advance for any assistance.
I dont know of a method in the API. but its so simple just create your own. Something like:
List<String> filenameAbsolute = new ArrayList<String>();
for ( String file: filenamesRelative ) {
filenameAbsolute.add(prefix + file);
}
Do it like this:
ArrayList<String> prefixAll(ArrayList<String> filenamesRelative)
{
ArrayList<String> filenamesAbsolute = new ArrayList<String>();
String includeDir = "/usr/local/boost-1.52.0/include";
for ( String file: filenamesRelative ) {
filenameAbsolute.add(includeDir + file);
}//for
return filenameAbsolute;
}//prefixAll()