break array into sub array - java

I have an array, for example:
{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }
I want to break it into sub array. When I do testing it, it displayed error:
java.lang.ArrayStoreException at line: String[] strarray = splitted.toArray(new String[0]);
Code:
public static String[] splittedArray(String[] srcArray) {
List<String[]> splitted = new ArrayList<String[]>();
int lengthToSplit = 3;
int arrayLength = srcArray.length;
for (int i = 0; i < arrayLength; i = i + lengthToSplit) {
String[] destArray = new String[lengthToSplit];
if (arrayLength < i + lengthToSplit) {
lengthToSplit = arrayLength - i;
}
System.arraycopy(srcArray, i, destArray, 0, lengthToSplit);
splitted.add(destArray);
}
String[] strarray = splitted.toArray(new String[0]);
return strarray;
}

From the java.lang.ArrayStoreException documentation:
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
You are attempting to store a String[][] into a String[]. The fix is simply in the return type, and the type passed to the toArray method.
String[][] strarray = splitted.toArray(new String[0][0]);

Change
String[] strarray = splitted.toArray(new String[0]);
to
String[][] split = new String[splitted.size()][lengthToSplit];
for (int index = 0; index < splitted.size(); index++) {
split[index] = splitted.get(index);
}
You'll need to change your return type to be String[][]

Related

How to Add elements at random positions in String array from a String ArrayList. In Android Java

I am new to android java. And this is bugging me.
Here, my ArrayList will have only 3 strings (black, grey, white). But please answer as if it had 100 or 1000 items. Then what would be the code to do that.
ArrayList<String> alCelebrityAllNAMES = new ArrayList<String>();
String myArray = {"1", "2", "3"};
public void regexImagesNames(){
Pattern patternNames = Pattern.compile("/images/banners/(.*?)_234x60.gif");
Matcher matcherNames = patternNames.matcher(fullHtmlCode);
while(matcherNames.find()) {
alCelebrityAllNAMES . add( matcherNames.group(1) ); //yields 3 words(strings)
}
}
This is how I would do it:
Solution 1, the long way...
String[] myArray = new String[]{"1", "2", "3"};
ArrayList<String> alCelebrityAllNAMES = new ArrayList<>(myArray.length);
ArrayList<Integer> alreadyOccupiedIndexes = new ArrayList<>();
for (int i = 0; i < myArray.length; i++)
{
String s = myArray[i];
int randomIndex = new Random().nextInt(myArray.length); // Getting a random index
if(!alreadyOccupiedIndexes.contains(randomIndex))
{
alCelebrityAllNAMES.add(randomIndex, s);
alreadyOccupiedIndexes.add(randomIndex);
i++;
}
}
Solution 2:
alCelebrityAllNAMES.addAll(Arrays.asList(myArray)); // Fill the arrayList with the elements of the array
Collections.shuffle(alCelebrityAllNAMES); // shuffle the elements in it..
// and if you need an array again:
alCelebrityAllNAMES.toArray();

Is it possible to remove string element in array of object using method? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
How to remove String element in array using different method. Any ideas on how to make it? I currently have this but it's not working and I'm out of ideas.
else if(operations ==2){
String searchStudentNumber = sc.next();
StudentAssistant[] copy = new StudentAssistant[studAssistant.length-1];
for(int i=0,j=0;i<studAssistant.length;i++){
if(copy[i]!= searchStudentNumber){
copy[j++] =
}
}
// for(int i = 0; i<sACounter; i++)
//// if(studAssistant[i].getStudentNumber().equals(searchStudentNumber)){
// if(studAssistant[i].equals(searchStudentNumber)){
//// studAssistant[i].searchStudentNumber(searchStudentNumber);
// studAssistant[i] = null;
// break;
// }
}
Do you need to use an Array? You can use List of String. One other possible solution could be to take the array and use 'Arrays.asList(yourArray)'. This will return a list. You can then remove the string you want to and then convert it back to an Array.
String stringArray[] = {"1","2","3"};
List<String> list = Arrays.asList(stringArray);
list.remove("2");
Object[] stringRemovedArray = list.toArray();
You should use a List instead if you want to delete elements.
List<String> list = new ArrayList<>(Arrays.asList("1", "2", "3", "4", "5"));
list.remove(0);//delete element at index 0
list.remove("3");//remove element with value "3"
System.out.println(list);
you can surely try to use Arrayutils lib from apache .
ArrayUtils.remove([1], 0) = []
ArrayUtils.remove([1, 2], 0) = [2]
ArrayUtils.remove([1, 2], 1) = [1]
ArrayUtils.remove([1, 2, 3], 1) = [1, 3]
maven dependency for apache commons will be
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
Using only arrays you could create one more with the same size and mark removed or free_noValue on second.(false)
public class ArrayTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayTest test = new ArrayTest();
MyArray myArr = test.new MyArray(3);
myArr.add(1, 0);
myArr.add(2, 1);
myArr.add(3, 2);
System.out.println(myArr);
myArr.remove(1);
System.out.println(myArr);
}
class MyArray
{
int arr[];
boolean abool[];
MyArray(int size)
{
arr=new int[size];
abool=new boolean[size];
}
public void add(int i,int pos)
{
//just replace any value if exists and mark as used
arr[pos]=i;
abool[pos]=true;
}
public void remove(int index)
{
abool[index]=false;
}
public String toString()
{
StringBuffer sb= new StringBuffer();
for(int i=0;i<arr.length;i++)
{
if(abool[i])
{
sb.append("arr["+i+"]="+arr[i]+"\n");
}
}
return sb.toString();
}
}
}
Output
arr[0]=1
arr[1]=2
arr[2]=3
//after remove 1_index
arr[0]=1
arr[2]=3
Basically all the values are on original array but show only the values where flag is true
In Java array is immutable, i.e. initialized array cannot change it's size. So to remove one element from the array, you have to create new one with size - 1 and copy all rest items to it.
String[] original = { "0", "1", "2", "3" }; // [ "0", "1", "2", "3" ]
String[] res = removeElement(original, 1); // [ "0", "2", "3" ]
public static String[] removeElement(String[] arr, int i) {
assert arr != null;
assert arr.length > 0;
assert i >= 0 && i < arr.length;
String[] res = new String[arr.length - 1];
System.arraycopy(arr, 0, res, 0, i);
System.arraycopy(arr, i + 1, res, i, arr.length - i - 1);
return res;
}
As alternative, you can do it using Apache ArrayUtils:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
String[] original = { "0", "1", "2", "3" }; // [ "0", "1", "2", "3" ]
String[] res = ArrayUtils.remove(original, 1); // [ "0", "2", "3" ]
Fortunately, there is ArrayList (along with other data types), that does all this internally:
List<String> original = Arrays.asList("0", "1", "2", "3"); // [ "0", "1", "2", "3" ]
original.remove(1); // [ "0", "2", "3" ]
Try to use code below
for(int i=0,j=0;i<studAssistant.length;i++){
if(!studAssistant[i].equals(searchStudentNumber)){
copy[j++] = studAssistant[i];
}
}

Java create object array of numbers in string format

I'm writing a function for a program and I need to generate a list of numbers in an Object[]
For example.
Object[] possibilities = functionName(13);
Should generate
Object[] possibilities = {"1", "2", "3","4","5","6","7","8","9","10","11","12","13"};
How should I go about achieving this?
String functionName(int number){
StringBuilder str = new StringBuilder("{");
for(int i = 1; i <= number; i++){
str.append(Integer.toString(i)).append(", ");}
String string = str.toString().trim();
string = string.substring(0, str.length()-1);
string += "}";
return string;
}
This should give you the desired string and you just print it.
First, you need a method to print the results from your functionName (that's setting a goal post). Something like,
public static void main(String[] args) {
Object[] possibilities = functionName(13);
System.out.println(Arrays.toString(possibilities));
}
Then you might implement functionName with a basic for loop like
static Object[] functionName(int c) {
Object[] ret = new String[c];
for (int i = 0; i < c; i++) {
StringBuilder sb = new StringBuilder();
sb.append("\"").append(i + 1).append("\"");
ret[i] = sb.toString();
}
return ret;
}
And when I run the above I get (the requested)
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
Try this method.
private Object[] function(int size) {
Object[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = Integer.toString(i + 1);
}
return result;
}
}

incorrect display GraphView(android)

Sorry for my English. I do not know why I did not properly displays a message GraphView. Now in the graph below displays constantly 1,1,1,1 ... Though would have 1,2,3,4 ...And evaluation are all 1. A shows the graph as 10. Why is it, tell me please.
GraphViewSeriesStyle seriesStyle = new GraphViewSeriesStyle();
BarGraphView graphView = new BarGraphView(this, "test");
//Our vertical graph
graphView.setVerticalLabels(new String[] { "10", "9", "8", "7", "6",
"5", "4", "3", "2", "1" });
//listMarks its ArrayList whith Marks
String[] array = new String[ listMarks.size() ];
//add marks in array
for(int i = 0; i < listMarks.size(); i++) {
array[i] = "1";
}
graphView.setHorizontalLabels(array);
seriesStyle.setValueDependentColor(new ValueDependentColor() {
#Override
public int get(GraphViewDataInterface data) {
return Color.rgb((int)(22+((data.getY()/3))), (int)(160-((data.getY()/3))), (int)(134-((data.getY()/3))));
}
});
GraphViewData[] data = new GraphViewData[array.length];
for (int a = 0; a < array.length; a++) {
data[a] = new GraphView.GraphViewData(a, Double.parseDouble(array[a]));
}
GraphViewSeries series = new GraphViewSeries("aaa", seriesStyle, data);
graphView.setManualYMinBound(0);
graphView.addSeries(series);
LinearLayout layout = (LinearLayout) findViewById(R.id.subLayout);
layout.addView(graphView);
Change:
array[i] = "1";
to:
array[i] = ""+i;
in the following loop"
//add marks in array
for(int i = 0; i < listMarks.size(); i++) {
array[i] = "1";
}

Converting Lists of Lists into String array

I want to convert lists of lists into two separate string arrays.
I want to convert taglist into string array TagArray[] and tokenlist into array called TokenArray.
I tried many ways but there are many ways to convert Converting an ArrayList into a 2D Array but I cannot find any method to convert Lists of lists to String array. Can anyone help me to do this.
taglist
[[NON, NON], [NON, NON ], [NON, NON, NON], [NON, NON] ,[ENTITY, ENTITY]]
tokenlist
[[John, ran], [John, jumped], [The, dog, jumped], [Mary, sat], [Finland, India]]
I tried the following way
for(int i=0;i<tokenlist.size();i++)
{
String[] words = tokenlist.get(i);
}
I am getting the output when i use above way. but the problem is that i have to take i th value from tokenlist and taglist at the same time
OR
I have to convert this into 3 D array which has the following format
static final String[][][] WORDS_TAGS = new String[][][]
{
{ { "John", "ran" }, { "NON", "NON" } },
{ { "John", "jumped"}, { "NON", "NON "} },
{ { "The", "dog", "jumped"}, { "NON", "NON", "NON" } },
{ { "Mary", "sat"}, { "NON", "NON"} },
{ { "Finland","India" }, { "ENTITY","ENTITY" } },
};
try this
List<List<String>> l1 = Arrays.asList(Arrays.asList("NON", "NON"),
Arrays.asList("NON", "NON"),
Arrays.asList("NON", "NON", "NON"),
Arrays.asList("NON", "NON"), Arrays.asList("ENTITY", "ENTITY"));
List<List<String>> l2 = Arrays
.asList(Arrays.asList("John", "ran"),
Arrays.asList("John", "jumped"),
Arrays.asList("The", "dog", "jumped"),
Arrays.asList("Mary", "sat"),
Arrays.asList("Finland", "India"));
String[][][] a = new String[l1.size()][][];
for (int i = 0; i < l1.size(); i++) {
a[i] = new String[][] {
l2.get(i).toArray(new String[l2.get(i).size()]),
l1.get(i).toArray(new String[l1.get(i).size()]) };
}
System.out.println(Arrays.deepToString(a));
output
[[[John, ran], [NON, NON]], [[John, jumped], [NON, NON]], [[The, dog, jumped], [NON, NON, NON]], [[Mary, sat], [NON, NON]], [[Finland, India], [ENTITY, ENTITY]]]
String[] words = new String[20];
int index = 0;
for(int i=0;i<L2.size();i++)
{
List l5 = (List)L2.get(i);
for(int j=0;j<l5.size();j++){
words[index] = (String)l5.get(j);
index++;
}
}
you need two for loop. one for external and another for internal
Try this
String[][][] newArray = new String[taglist.size()][2][];
for(int i=0;i<taglist.size();i++){
String[] arr=tokenlist.get(i).toArray(new String[tokenlist.get(i).size()]);
newArray[i][0]= arr;
arr= taglist.get(i).toArray(new String[taglist.get(i).size()]);
newArray[i][1]= arr;
}

Categories