I have got a String array:
String[] s={"one","two","three","four"};
Now I want to inspect from first three items of that array and do not want the inspection to include the fourth item.
I am using the following code to inspect:
boolean b = Arrays.asList(s).contains("two");
Wondering if there is a solution for this!
How about
String[] newArray=new String[3];
//Copy the first three elements into newArray
System.arraycopy(s,0,newArray,0,3);
After thinking a bit I figured a solution out without the need of creating new array:
int INSPECTION_LENGTH=3;
String query="two";
public static boolean b(String[] s,int length,String query){
for(int i=0;i<length;i++){
if(s[i].equals(query)){
return true;
}
}
return false;
}
Make a sub-list of List
If using a List such as ArrayList rather than a simple array, you can produce a sub-list that is based on the original but masks away unwanted elements.
Make a List from your array.
List < String > allStrings = new ArrayList<>( Arrays.asList( array ) ) ;
Of, if you want a non-modifiable list, use List.of.
List < String > allStrings = List.of( array ) ;
Get your sub-list, calling List::subList. We must use annoying zero-based index counting. The first number is inclusively the start. The second number is exclusively the end. So getting elements 1, 2, and 3 but not 4 and more translates as ( 0 , 3 ). I might be tempted to write this as ( 1 - 1 , 4 - 1 ) meaning “ordinal one inclusive to four exclusive, subtracting one for index counting”.
List< String > firstThreeStrings = allStrings.subList( 0 , 3 ) ; // Using annoying zero-based index counting. First number is inclusive while the second is exclusive.
Be aware that any changes to the original List will show through to the sub-list. We have not created a copy, we have a created second view onto the first list’s content, hiding unwanted elements.
Related
I'm currently learning in school but am unable to complete this part of the assignment.
An explanation with the use of for loops would be greatly appreciated.
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.
Because the number of elements in the merged array is unknown, its size should be set to the maximum possible number of elements it should contain, and after all elements which should form the merged array appear, any remaining unfilled spaces in the array should be 0. The first 0 encountered in the array should signal the end of the “actual” elements of the array, and therefore the 0s at the end of the array should not be printed by your program.
I propose to use a HashSet to remember which number you have already inserted into the array. For each number, you first check if the hash set already contains the number; if not, you add it to both the array and the set. For large inputs, this is much faster than checking the result array for each number. O(n*log(n)) or so (depending on how well the HashSet works for your input) instead of O(n^2).
#bubble
An example using a Set is very simple - however your teacher is asking for
an alternate list:
Integer[] one = new Integer[] {10,2,3,1};
Integer[] two = new Integer[] {3,8,5,4};
List<Integer> li_one = Arrays.asList(one); // First convert the arrays to a list
List<Integer> li_two = Arrays.asList(two);
Set<Integer> set = new HashSet<>();
set.addAll(li_one);
set.addAll(li_two);
System.out.println("The unique list is: " + set);
A HashSet was my first idea too, but the order of storing values depends
one hash values. The ... teacher likes to have alternating values which
I dont like to comment - because it is a really strange request.
Following code prints: merged list is: [1, 3, 2, 4, 5, 10, 8]
int[] one = new int[] {1,2,3,10};
int[] two = new int[] {3,4,5,8};
int one_len = one.length;
int two_len = two.length;
List<Integer> merged = new ArrayList<>();
int oneval,twoval;
for (int i = 0;i < one_len;i++)
{
oneval = one[i];
if (!merged.contains(oneval)) merged.add(oneval);
if (i < two_len)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
if (two_len > one_len)
{
for (int i = one_len; i < two_len;i++)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
System .out.println("merged list is: " + merged);
In a function,I want to initialise a java array of max size n, which is empty initially.If I add 3 elements(say n>3) and return the array, the array should contain only the 3 elements and not 3 elements followed by (n-3) 0's.
//PSEUDO CODE
func(){
//Create array A of max size 5
A[0]=1;
A[1]=2;
A[2]=3;
return A;
}
main(){
int[] B=func();
//B.length should give 3
for (int i=0;i<B.length;i++){
print B[i];
}
/*Should print 1 2 3
and Not 1 2 3 0 0
*/
}
And I don't want to use array list.I want to use java array only.
Your problem seems to be that you only want to print the non-default values of the array. If your values are always different from zero, then you can just do:
for (int i=0;i<B.length;i++){
if (B[i] != 0){
print(B[i]);
}
}
However, if your values can also be zero, you can also keep a counter of how many values you currently have, and only print that many values:
int counter = 3; //the array might be {1, 2, 3, 0, 0}
for (int i=0; i<counter; i++){
print(B[i]); //will print "1 2 3"
}
The counter must be incremented everytime you add a value.
Both solutions are limited though, depending on how you access and use the array.
then u have to make the array dynamic by urself. Everytime u add an element to the array create a new array of size=no of elements (let u r adding the 3rd element then size of new array would be 3). take the elements from old array to the new one. Each time u add 1 element u have to follow this.
Given two ArrayLists, one containing Strings whereas the other contains Integers.
The next step would be to grab the first position of each ArrayList and print them out side by side next to each other.
Then 2, 3, 4 , 5, You name it.
1st List: public List getDoubleHistory(){...}
2nd : List<StringBuilder> timeAtThatMoment = new ArrayList<>();
I guess that we start with a for loop in which i is the index.
First we have to assume that the lists are the same size, or else we cannot continue to do as you asked.
for (int i = 0; i < getDoubleHistory().size(); i++){
System.out.println(getDoubleHistory.get(i));
System.out.println(timeAtThatMoment.get(i));
}
If the lists are not the same size you will have to add some if statements to make sure you dont get index out of bounds exceptions.
You can read more on this here. https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html
I'm still learning about sorting and Arrays. Came up with this code which does sorting letters or numbers on ascending order but I really don't get the last part where System.out.println(SampleArray[i]);. Why is it SapleArray[i]? can someone enlighten me please.
public class TestClass {
public static void main(String[] args) {
String SampleArray[] = {"B","D","A","R","Z"};
Arrays.sort(SampleArray);
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
}
}
SampleArray refers to the whole array - here containing five strings.
SampleArray[0] refers to the first item in the array (here the string "B").
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
lets i take the values 0, 1, 2, 3, 4 one after another, so you print out first SampleArray[0]and then SampleArray[1] and so on until all the items have been printed.
You are trying to print an array, which is an ordered collection of items.
SampleArray[i] inside the loop lets you access one element at a time, in order.
More specifically, i takes on the values 0 through 4 in this case.
SampleArray[0] would give you the first element of SampleArray, because Java uses zero-based indexing for arrays.
Going through your code:
first you create a String array with those letters as element, which are saved like this: element 0 of array = B, element 1= D, etc. (in Arrays the counting always begin by 0 and not by 1).
Then it sort it in ascending order.
The for loop is there to print the sorted array, it iterate through the array beginning by element 0, until it is at the last element of the Array and it print these element.
The for loop does something over and over again.
The first part of the for loop, int i = 0 sets up a variable.
The second part i < SampleArray.length is the 'terminating condition' - it's the condition that has to remain true before each iteration of the loop.
The last part i++ is what happens after each iteration - i gets incremented.
So we are printing each element within SampleArray. i goes between 0 and the one less than the number of elements in the array. (e.g. if the array contained 4 elements, i would be 0 to 3, which is what we want).
And in the body of the loop, the [i] bit selects that element from SampleArray, and that is the value that gets printed on each line.
Another way of looking at it: SampleArray supports the [] operator, which when applied, will return an element from the array.
(I'm new at Java, coming over from Python ---)
I'm going through a tutorial and they've created a program which counts how many times a number appears in a file, then returns that number. One particular part of the program is somewhat mysterious to me and deals with the ArrayList's .get and .set (methods? functions?). The program goes like this:
// (Scan a file with the numbers, say, 2 2 3 4, and put it into data1 variable.)
// (Make An Empty ArrayList with a bunch of 0's)
Scanner data1 = null;
ArrayList<Integer> count = new ArrayList<Integer>();
Integer idx;
while(data1.hasNextInt()){
idx = data1.nextInt();
System.out.println(idx);
System.out.println(count.get(idx)+1);
count.set(idx,count.get(idx)+1);
}
//Then prints out all the values; the ArrayList contains the number of times the number n occurs in the n-th index.
My question comes at the "while" part. For concrete, let's assume data1 has the numbers 2 2 3 4. It seems that it takes idx = 2, then puts a 1 in count[2], which is reasonable. It then takes idx = 2 again (the next integer in data1) and puts a 2 in count[2], which is also reasonable. At this point, the next number in data1 makes idx = 3, but it occurs at the index 2 in the ArrayList, so it should put a 3 in count[3], which is incorrect.
So, what is .get and .set doing here? Do they pop the elements off of the list when they're done with it? Am I overlooking something?
A .get() will not automagically get elements from a List which does not have that many elements. Note: list indices, like arrays, start at 0.
If you do:
final List<Integer> = new ArrayList<Integer>();
list.get(0);
this is a runtime error (IndexOutOfBoundsException) because your list has no elements.
You have to fill it:
list.add(1); // append an element
list.get(0); // returns element at index 0
list.get(1); // IndexOutOfBoundsException!
The .set() method takes an index and a value at an argument. In a similar vein, you cannot set an element which does not already exist, except at the very end of the list:
// start from an empty list
list.set(1, 32); // IndexOutOfBoundsException!
list.set(0, 32); // OK
Final note: try not to use list[i], bracket indices are used for arrays ;) Note that arrays are not resizabe in Java. Lists (which are an implementation of a Collection), however, are. But you must append to them.
So, what this line does:
count.set(idx, count.get(idx) + 1);
is take the value at index idx, add 1 to it, and sets back this value at the same index.
In your specific case, what you are looking for is a sparse array. In Java we use a HashMap<Integer, Integer> for that purpose. You don't need any initialization with zeros, but you do need to check for null:
final Integer curr = count.get(idx);
count.put(idx, curr == null? 1 : curr+1);
You are currently using an ArrayList, which acts like an array, but makes it easier to expand it - for example, add elements to it.
What you want is the java equivalent of the python dict, a key/value storage, in java, this is called a HashMap<K,V> (docs).
Scanner data1 = null;
HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
Integer idx;
while(data1.hasNextInt()) {
idx = data1.nextInt();
System.out.println(idx);
Integer g = count.get(idx)+1;
if(g == null) {
g = 0;
}
g++;
System.out.println(g);
count.put(idx, g);
}