Java, Create array if it doesn't already exist - java

I couldn't find anything on that while googling
so
I want to create an array only if it doesn't already exists.
EDIT: I mean not initialized
I know how to check for values in the array
Should be simple but I'm stuck
best regards
static long f(long n) {
int m = (int)n;
**if (serie == null) {
long[] serie = new long[40];
}**
if (n == 0) {
return 0;
}
else if (n==1) {
return 1;
}
else {
long asdf = f(n-1)- 2*(f(n-2)) + n;
return asdf;
}
}
something like that
a recursive function and I want to save the values in an array

You are trying to use the serie array but it is not yet declared. First declare it and then use it, as you want.

Are you looking for:
if (values == null)
{
values = new int[10];
}
or something like that? If not, please edit your question to provide more information.
EDIT: Okay, judging by the updated question, I suspect you ought to have two methods:
static long f(long n)
{
return f(n, new long[40]);
}
static long f(long n, long[] serie)
{
// Code as before, but when you recurse, pass in serie as well
}
(Note that your current code doesn't use serie at all.)

if(array==null){
//create new array
}

AFAIK, there are, if you use a variable in java, it is initialized. So you probably want to check if that variable, an array in this case, is null. Not only that, you can and probably should check if it is an array. Arrays are objects in java. So you could do something like this for an array:
if(!obj.getClass().isArray())

Related

How do you find the index of the value(a String Value) from an arrayList? [duplicate]

For an Android app, I have the following functionality
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?
ArrayList has a indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
If your List is sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch. Otherwise, you should use List.indexOf, as others have pointed out.
But your algorithm is sound, fwiw (other than the == others have pointed out).
Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
Use indexOf() method to find first occurrence of the element in the collection.
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2

How to make an addAll() or addRange() method from scratch in java?

I'm trying to do a linkedlist for an assigment i have, this ask explicitly to create, from scratch a linkedlist and some derivated types like a queue and a stack, this is just some college homework, and i realize how to make a node class and a linkedlist class, but i'm struggling to create the addAll() method in this linkedlist class, this is what i have.
if i must bet, i say is the Collection c one, but then, i'm trying to add list of stuff there, in order to pass him's content to the new list, obiusly is not ready and obiusly doesn't work.
Can you tell me how i can pass some kind of "proto-list" in order to pass them data inside the new list?
(I know i must use somekind of for(objects) but i'm failing to pass some data through the parameter, which will be the right parameter to put there?)
public boolean addAll(Collection c) {
for (int i = 0; i < (this.listaNodos.size()); i++) {
//for (T someT : c){
// Node newNodo = new Node(someT);
//}
//i know the one down there is not gonna do anything, because
//i'm not accesing the data, but one problem at a time would ya ;)
Node newNodo = new Node(someT);
Node actualNodo = this;
boolean processFinished = false;
try{
if(index >= this.listaNodos.size() || index < 0){
throw new IndexOutOfBoundsException();
}
do{
if(index == actualNodo.getIndex())
{
actualNodo.setData(someT);
processFinished = true;
return true;
}
else
{
actualNodo = actualNodo.nextNode;
}
}while(!processFinished);
return false;
}catch(IndexOutOfBoundsException ex)
{
throw ex;
}
}
return false;
}
Can you tell me how to fix it to make it work?
Any request for clarification, constructive comment, or question would be greatly apreciated too.
Thanks in advance
I assume you already have an add() method of some sort right? If so, you can go over each element in c and add it using the add method:
public boolean addAll(Collection<T> c) {
boolean changed = false;
for (T t:c) {
changed |= this.add(t);
}
return changed;
}
I'm assuming the returned boolean means whether this list has changed, this is how it is defined in the Collection contract: https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#addAll(java.util.Collection).
You were also missing a generic type for your add method, so I added one. I assume your class definition looks somthing like this?
public class MyLinkedList<T>

How can I refactor a `for` loop?

Problem
I want to be able to split up a for loop into a method, then put the for the method in the for loop to make it easier to read. Below demonstrates this:
Example.java
for(int member = firstMember; member < arrayOfMembers.length; member++) {
[...] other code
}
Should be refactored to:
Solution Example:
private boolean eachMemberInList() {
return int member = firstMember; member < arrayOfMembers.length; member++);
}
public static void main(String[] args) {
for(eachMemberInList());
}
Is this possible?
No, you cannot return or otherwise manipulate a for loop as if it were an object in Java.
However, what you're attempting to do is unnecessary. You can use an array directly in an "enhanced" for loop, since Java 1.5.
for (int member : arrayOfMembers) { ... }
It is more concise than attempting to create a method to manipulate a for loop, and it is even more concise than the standard for loop you're attempting to replace.
What you're talking about is turning a for loop, into a while loop.
for (; true; )
is equivalent to
while (true)
So, you're solution could be viewed as
while (someFunctionIsTrue()) {}
Don't want to get into religious debates here, but generally, if you're iterating over an array of objects, you really do want to use a for lop. Not necessarily because it's any different than a while loop using your solution, but because it's idiomatic. When a developer (an experienced developer) sees a for loop, the fact that you chose a for loop tells them something. It says, hey, I'm iterating over the objects of a container. What a while loop says, is that there is some condition, and while that condition is true do something.
While loops and for loops are identically in capability. By using them idiomatically, you can communicate your code more concisely and clearly. For example:
int index = 0;
while (index < array.size) {
doSomethingWithArrayElement(array[index]);
index++;
}
This is not concise. The hanging variable declaration creates an extra line of code, as does the index++ at the end. When you do this:
for(int i = 0; i < array.size; i++) {
doSomething(array[i]);
}
This is very concise, and your use of a for loop... if used concistently like this, immediately tells a developer that all items of this container are going to have something done with them!
Now let's use the alternate example, where we have a function that returns a boolean. And this boolean tells the loop whether to continue or not. We could do something like this:
int index = 0;
for (; doSomethingWithArrayItem(array, index); index++){
}
boolean doSomethingWithArrayItem(array, index) {
//blah blah blah
if (index + 1 == array.size) return false;
return true;
}
This accomplishes what you want, but is difficult logic to follow. Let's say that you named your doSomething function something useful, like
incrementValueByTwo(item);
What do you think this function does? It's pretty clear right. Now, let's place this function in the for loop above:
int index = 0;
for (; incrementValueByTwo(array, index); index++){
}
How many values are we incrementing? Are we incrementing all the values of the array by 2? Some of them? The first one? Or perhaps none of them under certain circumstances? THIS IS VERY CONFUSING!!!! DON'T DO THIS!
I would rather do something like
String[] array = new String[10];
for(String variable : array){
doSomething(variable);
}
Or if you are using Java 8 then
Arrays.stream(array).forEach(memberOfArray -> doSomething(memberOfArray));
This is much more readable.

Better way to find index of item in ArrayList?

For an Android app, I have the following functionality
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?
ArrayList has a indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
If your List is sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch. Otherwise, you should use List.indexOf, as others have pointed out.
But your algorithm is sound, fwiw (other than the == others have pointed out).
Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
Use indexOf() method to find first occurrence of the element in the collection.
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2

Casting a Object to HashMap

I'm having trouble working out how to count instances of Values in a HashMap.
I have seen that there is methods attached to the Object class that look as if they are able to help me, so I've tried to cast those in to work but I must be doing something wrong somewhere.
If there's an easier way, I haven't found it yet. NB: Library is my HashMap.
public void borrowBooks(String id, String name, String sid, String sname) {
if((getKeyFromValue(Books, name).equals(id))&&(getKeyFromValue(Students, sname).equals(sid))){
if((Object)Library.countValues(sid)!=5){
Library.put(id, sid);
}
else{
System.out.println("You have exceeded your quota. Return a book before you take one out." );
}
}
}
Which doc are you looking at ? The Javadoc for Hashmap doesn't specify a countValues() method.
I think you want a HashMap<String, List<String>> so you store a list of books per student (if I'm reading your code correctly).
You'll have to create a list per student and put that into the HashMap, but then you can simply count the entries in the List using List.size().
e.g.
if (Library.get(id) == null) {
Library.put(id, new ArrayList<String>());
}
List<String> books = Library.get(id);
int number = books.size() // gives you the size
Ignoring threading etc.
First: There is (almost) no point in ever casting anything to Object. Since everything extends Object, you can always access the methods without casting.
Second: The way you're casting actually casts the return value, not the Library. If you were doing a cast that was really necessary, you would need an extra set of parentheses:
if(((Object)Library).countValues(sid) != 5)
Third: There is no countValues method in either HashMap or Object. You'll have to make your own.
This is the general algorithm to use (I'm hesitant to post code because this looks like homework):
initialize count to 0
for each entry in Library:
if the value is what you want:
increment the count
int count = 0;
for(String str : Library.values())
{
if(str == sid)
count++;
if(count == 5)
break;
}
if(count < 5)
Library.put(id, sid);
else
System.out.println("You have exceeded your quota. Return a book before you take one out." );

Categories