java - Array CompareFind Equals words only using array not array list -
have 2 text file words list. need save both file in 2 array.i know how using list , set.. here want know how using arrays.only array , no predefined functions such arrays.sort() or collections.sort() can used
no list no arraylist or no class java collection frameworks can used.
public class main { public static set<string> setlist1= new hashset<>(); public static string[] arraylist=new string[file1count]; public static string[] array2=new string[file2count]; public static int file1count=0; public static int file2count=0; public static void main(string[] args) { try { /*read files*/ scanner rf= new scanner(new bufferedreader(new filereader("d:\\iit\\project save\\new\\inteli j\\oopworkshop01\\file1.txt"))); scanner rf2= new scanner(new bufferedreader(new filereader("d:\\iit\\project save\\new\\inteli j\\oopworkshop01\\file2.txt"))); string line; string line2; while(rf.hasnext()){ line=rf.nextline(); file1count++; } while(rf2.hasnext()){ line2=rf2.nextline(); file2count++; } rf.close(); rf2.close(); }catch(ioexception e){ system.out.println(e); } } }
the problem using arrays don't know in advance length allocate.
you have 2 options:
- read each file twice
- allocate array of initial length, , reallocate needed (that's arraylist does.)
second option: let's have method readfile reads lines file , returns array:
public static string[] readfile(string filename) throws ioexception { try (reader reader = new filereader(filename); bufferedreader in = new bufferedreader(reader)) { string[] lines = new string[10]; // start 10 int count = 0; string line; while ((line = in.readline()) != null) { if (count >= lines.length) { lines = reallocate(lines, count, 2*lines.length); } lines[count++] = line; } if (count < lines.length) { // reallocate final length; lines = reallocate(lines, count, count); } return lines; } } private static string[] reallocate(string[] lines, int count, int newlength) { string[] newarray = new string[newlength]; (int = 0; < count; ++i) { newarray[i] = lines[i]; } lines = newarray; return lines; }
Comments
Post a Comment