Hi I am new to programming.I am trying to create a android project like contanct list.I am generating data for the adapter class. I am getting IndexOutOfBoundsException. I know this is basic of java but I am unable to figure it out why i am getting this error. Thanks in advance.
Here is my code:
// How i am setting adapter from activity
customAdapter = new CustomAdapter(getActivity(), getDataSetForPojo(), mSectionsForPojo, mMapIndexForPojo);
mRecyclerView.setAdapter(customAdapter);
// Getting List for the adapter
private ArrayList<Pojo> getDataSetForPojo() {
List<Pojo> pojoList = genData();
getListIndexedForPojo(pojoList);
ArrayList results = new ArrayList<>();
ElementList obj;
int section = 0;
int normal = 0;
String str;
String ch;
int total = pojoList.size() + mSectionsForPojo.length;
for (int index = 0; index < total; index++) {
str = pojoList.get(normal).getStr(); //here I am getting error
ch = str.substring(0, 1);
if (index == 0 || ch.equals(mSectionsForPojo[section])) {
obj = new ElementList(ch, true);
mMapIndexForPojo.put(ch, index);
if (section < mSectionsForPojo.length - 1) {
section++;
} else {
section = 0;
}
} else {
obj = new ElementList(pojoList.get(normal).getStr(), false);
normal++;
}
results.add(index, obj);
}
return results;
}
// Generating list for the section
public void getListIndexedForPojo(List<Pojo> fruitList) {
mMapIndexForPojo = new LinkedHashMap<>();
for (int x = 0; x < fruitList.size(); x++) {
String str = fruitList.get(x).getStr();
String ch = str.substring(0, 1);
ch = ch.toUpperCase(Locale.US);
// HashMap will prevent duplicates
mMapIndexForPojo.put(ch, x);
}
Set<String> sectionLetters = mMapIndexForPojo.keySet();
// create a list from the set to sort
ArrayList<String> sectionList = new ArrayList<>(sectionLetters);
Collections.sort(sectionList);
mSectionsForPojo = new String[sectionList.size()];
sectionList.toArray(mSectionsForPojo);
}
// Generating DATA
private List<Pojo> genData() {
List<Pojo> pojoList = new ArrayList<>();
Pojo pojo;
pojo = new Pojo();
pojo.setId(1);
pojo.setStr("aback");
pojoList.add(pojo);
// adding more objects to list.
return pojoList;
}
I think the problem is your for loop in method "getDataSetForPojo()" is running more than the size of pojoList.
private ArrayList<Pojo> getDataSetForPojo() {
...
List<Pojo> pojoList = genData();
...
// total can have larger value than pojoList.size() if mSectionsForPojo.length isn't zero.
int total = pojoList.size() + mSectionsForPojo.length;
for (int index = 0; index < total; index++) {
str = pojoList.get(normal).getStr(); //here I am getting error
if (index == 0 || ch.equals(mSectionsForPojo[section])) {
} else {
...
normal++;
}
}
return results;
}
So it is possible that normal can be incremented more than pojoList size.
I want to remove duplicate row in a 2d array . i tried the below code .but it is not working . please help me .
Input :
1,ram,mech
1,ram,mech
2,gopi,csc
2.gopi,civil
output should be :
1,ram,mech
2,gopi,csc
2.gopi,civil
Code :
package employee_dup;
import java.util.*;
public class Employee_dup {
public static void main(String[] args)
{
boolean Switch = true;
System.out.println("Name ID Dept ");
String[][] employee_t = {{"1","ram","Mech"},{"1","siva","Mech"},{"1","gopi","Mech"},{"4","jenkat","Mech"},{"5","linda","Mech"},{"1","velu","Mech"}};
int g = employee_t[0].length;
String[][] array2 = new String[10][g];
int rows = employee_t.length;
Arrays.sort(employee_t, new sort(0));
for(int i=0;i<employee_t.length;i++){
for(int j=0;j<employee_t[0].length;j++){
System.out.print(employee_t[i][j]+" ");
}
System.out.println();
}
List<String[]> l = new ArrayList<String[]>(Arrays.asList(employee_t));
for(int k = 0 ;k < employee_t.length-1;k++)
{
if(employee_t[k][0] == employee_t[k+1][0])
{
System.out.println("same value is present");
l.remove(1);
array2 = l.toArray(new String[][]{});
}
}
System.out.println("Name ID Dept ");
for(int i=0;i<array2.length;i++){
for(int j=0;j<array2[0].length;j++){
System.out.print(array2[i][j]+" ");
}
System.out.println();
}
}
}
class sort implements Comparator {
int j;
sort(int columnToSort) {
this.j = columnToSort;
}
//overriding compare method
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[j].compareTo(row2[j]);
}
}
First I sorted the array based on column one ,then tried to remove duplicates by checking the first column elements and seconds column elements but it is not removing the required column but remove other columns.
You may give this solution a try:
public static void main(String[] args) {
String[][] employee_t = {
{"1","ram","Mech"},
{"1","ram","Mech"},
{"1","siva","Mech"},
{"1","siva","Mech"},
{"1","gopi","Mech"},
{"1","gopi","Mech"} };
System.out.println("ID Name Dept");
Arrays.stream(employee_t)
.map(Arrays::asList)
.distinct()
.forEach(row -> System.out.printf("%-3s%-7s%s\n", row.get(0), row.get(1), row.get(2)));
}
Output
ID Name Dept
1 ram Mech
1 siva Mech
1 gopi Mech
How it works: comparing arrays does rely on instance equality and not on comparing contained elements by equals. Hence converting each row of your 2D array into a List will enable you to compare lists, which takes equals of the elements contained into account.
The Java Stream API does provide a method distinct which relies on equals and will remove all duplicates for you.
Based on your code. Maybe it is not the BEST solution but it works.
public static void main(String[] args) {
System.out.println("Name ID Dept ");
// I added duplicated rows
String[][] inputArray = {
{ "1", "ram", "Mech" },
{ "1", "siva", "Mech" },
{ "1", "gopi", "Mech" },
{ "1", "gopi", "Mech" },
{ "4", "jenkat", "Mech" },
{ "5", "linda", "Mech" },
{ "1", "velu", "Mech" },
{ "1", "velu", "Mech" }
};
// I will add all rows in a Set as it doesn't store duplicate values
Set<String> solutionSet = new LinkedHashSet<String>();
// I get all rows, create a string and insert into Set
for (int i = 0 ; i < inputArray.length ; i++) {
String input = inputArray[i][0]+","+inputArray[i][1]+","+inputArray[i][2];
solutionSet.add(input);
}
// You know the final size of the output array
String[][] outputArray = new String[solutionSet.size()][3];
// I get the results without duplicated values and reconvert it to your format
int position = 0;
for(String solution : solutionSet) {
String[] solutionArray = solution.split(",");
outputArray[position][0] = solutionArray[0];
outputArray[position][1] = solutionArray[1];
outputArray[position][2] = solutionArray[2];
position++;
}
System.out.println("Name ID Dept ");
for (int i = 0; i < outputArray.length; i++) {
for (int j = 0; j < outputArray[0].length; j++) {
System.out.print(outputArray[i][j] + " ");
}
System.out.println();
}
}
I have posted what I think is a readable and easy to maintain solution.
I decided to use distinct from Stream which is part of Java 8
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream. - https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--
Main.class
class Main {
public static void main(String[] args)
{
//Create a list of Employee objects
List<Employee> employeeList = new ArrayList<Employee>();
Employee e1 = new Employee(1, "ram", "mech");
Employee e2 = new Employee(1, "ram", "mech");
Employee e3 = new Employee(2, "gopi", "csc");
Employee e4 = new Employee(2, "gopi", "civil");
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
System.out.println("Before removing duplicates");
employeeList.stream().forEach(System.out::println);
//This is where all the magic happens.
employeeList = employeeList.stream().distinct().collect(Collectors.toList());
System.out.println("\nAfter removing duplicates");
employeeList.stream().forEach(System.out::println);
}
}
Output:
Before removing duplicates
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=2, valB=gopi, valC=csc]
Employee [valA=2, valB=gopi, valC=civil]
After removing duplicates
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=2, valB=gopi, valC=csc]
Employee [valA=2, valB=gopi, valC=civil]
Employee.class
//This is just a regular POJO class.
class Employee {
int valA;
String valB, valC;
public Employee(int valA, String valB, String valC){
this.valA = valA;
this.valB = valB;
this.valC = valC;
}
public Employee(Employee e) {
this.valA = e.valA;
this.valB = e.valB;
this.valC = e.valC;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + valA;
result = prime * result + ((valB == null) ? 0 : valB.hashCode());
result = prime * result + ((valC == null) ? 0 : valC.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof Employee && ((Employee)obj).hashCode() == this.hashCode()){
return true;
}
return false;
}
#Override
public String toString() {
return "Employee [valA=" + valA + ", valB=" + valB + ", valC=" + valC + "]";
}
}
Pre Java - 8 solution. May not be the best way. But a quick solution which works..
String[][] records = {
{"1","ram","Mech"},
{"1","ram","Mech"},
{"1","gopi","csc"},
{"1","gopi","civil"} };
List<String[]> distinctRecordsList = new ArrayList<String[]>();
for(String[] record : records){
if(distinctRecordsList.size()>0){
boolean sameValue = false;
for(String[] distinctRecord : distinctRecordsList){
int distinctRecordFields = distinctRecord.length;
if(record.length==distinctRecordFields){
for(int k=0;k<distinctRecordFields;k++){
sameValue = record[k].equalsIgnoreCase(distinctRecord[k]);
if(!sameValue)
break;
}
}else
throw new Exception("Can't compare the records");
}
if(!sameValue)
distinctRecordsList.add(record);
}else if(distinctRecordsList.size()==0)
distinctRecordsList.add(record);
}
Object[] distRecObjects = distinctRecordsList.toArray();
String[][] distinctRecordsArray = new String[distRecObjects.length][];
int i=0;
for(Object distRecObject : distRecObjects){
distinctRecordsArray[i] = (String[]) distRecObject;
i++;
}
Contrary to some other answers I will try to explain what went wrong in your own code and how to fix it within your code (I agree very much with kkflf that an Employee class would be a huge benefit: it’s more object-oriented and it will help structure the code and give better overview of it).
The issues I see in your code are:
You are not removing the correct element when you detect a duplicate, but always the element at index 1 (the second element since indices count from 0). This isn’t trivial, though, because indices shift as you remove elements. The trick is to iterate backward so only indices that you are finished with shift when you remove an element.
You are using == to compare the first element of the subarrays you are comparing. If you wanted to compare just the first element, you should use equals() for comparison. However, I believe you want to compare the entire row so 2,gopi,csc and 2.gopi,civil are recognized as different and both preserved. Arrays.equals() can do the job.
You need to create array2 only after the loop. As your code stands, if no duplicates are detected, arrays2 is never created.
So your loop becomes:
for (int k = employee_t.length - 1; k >= 1; k--)
{
if (Arrays.equals(employee_t[k], employee_t[k - 1]))
{
System.out.println("same value is present");
l.remove(k);
}
}
array2 = l.toArray(new String[][]{});
This gives you the output you asked for.
Further tips:
Your comparator only compares one field in the inner arrays, which is not enough to guarantee that identical rows come right after each other in the sorted array. You should compare all elements, and also require that the inner arrays have the same length.
Use generics: class Sort extends Comparator<String[]>, and you won’t need the casts in compare()
According to Java naming conventions it should be class EmployeeDup, boolean doSwitch (since switch is a reserved word) and class Sort.
You are not using the variables Switch and rows; delete them.
I have wrote a solution for me. This may not be the best but it works.
public static String[][] removeDuplicate(String[][] matrix) {
String[][] newMatrix = new String[matrix.length][matrix[0].length];
int newMatrixRow = 1;
for (int i = 0; i < matrix[0].length; i++)
newMatrix[0][i] = matrix[0][i];
for (int j = 1; j < matrix.length; j++) {
List<Boolean> list = new ArrayList<>();
for (int i = 0; newMatrix[i][0] != null; i++) {
boolean same = true;
for (int col = 2; col < matrix[j].length; col++) {
if (!newMatrix[i][col].equals(matrix[j][col])) {
same = false;
break;
}
}
list.add(same);
}
if (!list.contains(true)) {
for (int i = 0; i < matrix[j].length; i++) {
newMatrix[newMatrixRow][i] = matrix[j][i];
}
newMatrixRow++;
}
}
int i;
for(i = 0; newMatrix[i][0] != null; i++);
String finalMatrix[][] = new String[i][newMatrix[0].length];
for (i = 0; i < finalMatrix.length; i++) {
for (int j = 0; j < finalMatrix[i].length; j++)
finalMatrix[i][j] = newMatrix[i][j];
}
return finalMatrix;
}
This method will return a matrix without any duplicate rows.
What's the easiest and most effective way to spit a string into different arrays of types? Example:
String[] textArr;
String[] numbersArr;
and if possible a String[] doubleArr and a String[] dateArrayz
//the string I want to split
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
After it's split it should be
String[] textArr = ["Tinus","has","issues","and","to","pay","for","on"];
String[] numbersArr = ["99","26"];
String[] doubleArr = ["2200.50"];
String[] dateArr = ["2016/10/10"];
I might opt for just splitting the input string by space, and then using a pattern match to check each entry to determine where it belongs:
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
String[] parts = splitMe.split(" ");
List<String> textList = new ArrayList<>();
List<String> numbersList = new ArrayList<>();
List<String> currencyList = new ArrayList<>();
List<String> dateList = new ArrayList<>();
for (String part : parts) {
if (part.matches("\\d*")) {
numbersList.add(part);
}
else if (part.matches("\\$\\d*\\.\\d*")) {
currencyList.add(part);
}
else if (part.matches("\\d{4}/\\d{2}/\\d{2}")) {
dateList.add(part);
}
else {
textList.add(part);
}
}
I didn't attempt to formally extract a double from the currency. And I also chose to use lists rather than arrays to store the various terms, because this will scale better. I will leave it up to you to fill in the details.
You can try something like this:
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
String[] splitArray = splitMe.split(" ");
System.out.println("splitArray: " + Arrays.toString(splitArray));
String[] tmp = new String[splitArray.length];
int i = 0;
for (String s : splitArray) {
if (s.matches("[A-Za-z]+")) {
tmp[i] = s;
i++;
}
}
String[] textArr = new String[i];
for (int j = 0; j < textArr.length; j++) {
textArr[j] = tmp[j];
}
tmp = new String[splitArray.length];
i = 0;
for (String s : splitArray) {
if (s.matches("[0-9]+")) {
tmp[i] = s;
i++;
}
}
String[] numbersArr = new String[i];
for (int j = 0; j < numbersArr.length; j++) {
numbersArr[j] = tmp[j];
}
tmp = new String[splitArray.length];
i = 0;
for (String s : splitArray) {
if (s.matches("\\$[0-9]+\\.[0-9]+")) {
tmp[i] = s;
i++;
}
}
String[] doubleArr = new String[i];
for (int j = 0; j < doubleArr.length; j++) {
doubleArr[j] = tmp[j];
}
tmp = new String[splitArray.length];
i = 0;
for (String s : splitArray) {
if (s.matches("[0-9]+/[0-9]+/[0-9]+")) {
tmp[i] = s;
i++;
}
}
String[] dateArr = new String[i];
for (int j = 0; j < dateArr.length; j++) {
dateArr[j] = tmp[j];
}
System.out.println("textArr: " + Arrays.toString(textArr));
System.out.println("numbersArr: " + Arrays.toString(numbersArr));
System.out.println("doubleArr: " + Arrays.toString(doubleArr));
System.out.println("dateArr: " + Arrays.toString(dateArr));
Please note that the regex used are not ideal but they work for your case. I used arrays because I thought it is a strict requirement. You can use lists as well which is better.
I would like to create a code that will help me copy elements from the 'allWords' ArrayList to the 'distinctWords'. but his time in the distinct words ArrayList I want a word to appear just one, eliminating redundancy in the "distinctWords' ArrayList.
this is the code that I have come up with and I am getting no output.
import java.util.ArrayList;
public class copyElements {
static ArrayList<String> distinctWords = new ArrayList<String> ();
static ArrayList<String> allWords = new ArrayList<String> ();
static int allWordsCount = 0;
static int distinctWordsCount;
static int tracker;
public static void main(String[] args) {
allWords.add("you");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("dubai");
allWords.add("and");
allWords.add("you");
allWords.add("also");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("seychelles");
//printing all items in the 'allwords' arraylist
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
distinctWords.add(0,allWords.get(0));
distinctWordsCount = 1;
int i = 1;
for(int j = 1; j <= distinctWords.size(); j++){
if(i < allWords.size()){
tracker = 0;
if (tracker == j){
distinctWords.add(j, allWords.get(i));
System.out.println("\t\t\t" + distinctWords.get(j));
distinctWordsCount ++;
i++;
} else
if (tracker != j){
if(allWords.get(i) != distinctWords.get(tracker)){
//distinctWords.add(allWords.get(i));
//distinctWordsCount ++;
tracker++;
}
else
if(allWords.get(i) == distinctWords.get(tracker)){
i++;
}
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
//System.out.println("\t\t\t" + distinctWords.get(j));
}
}
//System.out.println("\t\t\t" + distinctWords.get(j));
}
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'ALLWORDS' ARRAYLIST IS : " + allWords.size());
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'DISTINCTWORDS' ARRAYLIST IS : " + allWords.size());
System.out.println("\n\nITEMS IN THE 'DISTINCTWORDS' ARRAYLIST ARE : " + distinctWords.size());
}
}
How about the following code:
for (int i = 0, size = allWords.size(); i < size; i++)
{
String word = allWords.get(i);
// add the word if it is not in distinctWords
if (!distinctWords.contains(word))
{
distinctWords.add(word);
}
}
If you don't care about the order of the words, then you could use a Set as suggested.
Set<String> distinctSet = new HashSet<String>(allWords);
// if you want the set put into your other arrayList
distinctWords.addAll(distinctSet);
//al1 and al2 are ArrayList<Object>
for(Object obj:al1){
if(!al2.contains(obj))
al2.add(obj);
}
I think this can give you a set of all distinct words.
Set<String> distinctWords = new HashSet<>(allWords);
If you do need an array, you can simple do this:
ArrayList<String> distinctWordsArr = new ArrayList<>(distinctWords);
public boolean makeReservation(int id, AvilaNatalyPassenger request) {
boolean status = true;
ArrayList<Integer> inputValues = new ArrayList<Integer>();
for (int i = 0; i < 22; i++) {
for (int j = 0; j < 5; j++) {
id = seats[i][j];
if (id != -1) {
if (inputValues.contains(id)) {
status = false;
break;
}
else {
inputValues.add(id);
for(int a = 0; a < inputValues.size; a++)
seats[a] = inputValues[a];
}
}
}
}
return status;
}
This is what I have but its not correct. I need to add what I have in inputVaule arrayList into the array seats.
You can also look at the Java API: http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html
public Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
So this is what you could do:
seats[a] = inputValues.toArray();
Furthermore you cannot use inputValues[a] since it is not an array. What you probably could do is
seats[a] = (inputValues.toArray())[a];
To answer your question, here is an example:
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Example is taken from here