Pergunta de entrevista da empresa Barclays

Assume there is a method provided getNextperson() which gives Person objects which have comparable interface implemented, now read from a file records and sort it and give first 1000 records, write code on the paper

Respostas da entrevista

Sigiloso

8 de abr. de 2010

The question is actually quite simple since you were given that Comparable interface is already implemented (eg, public int compareTo(Object o) method is overridden in Person object). First step, 'read from a file all records' and store each Person object returned by getNextPerson() in List records = new ArrayList(). Next step, call Collections.sort(records) to sort (by criteria specified in compareTo() method, such as Last and First name, or any other meaningful parameter). Final step, 'give first 1000 records' -- either by iterating over first 1000 (checking size() >= 1000) or by returning the list consisting of only 1000 records (either copy into a new list with size 1000 or by using removeRange method in ArrayList.

6

Sigiloso

15 de jan. de 2010

maybe use tree data structure

2

Sigiloso

24 de fev. de 2010

tree data structure ? i hope u meant to say "TreeSet"; but the question doesnt say that getNextPerson() will be unique. So let us not bank on treeSet. So just add them on to a arrayList and do a Collections.sort(arrayList);

Sigiloso

28 de abr. de 2011

Use a heap based data structure(min or max) to keep replacing the root once you have a 1000 records. java priority queue.

1

Sigiloso

6 de fev. de 2019

Using heap is the rightapproach. Array list approach wont work if the file is so huge. Implementing heap using array to store the top 1000 records. (note: since the person implements comparable, we just have to compare the new person with root node i.e index 0 in heap. if root is already greater than new person, just skip the new person else add it as root and call heapify). Finally we can call the Arrays.sort on heap and return the result.

Sigiloso

24 de mai. de 2010

How would you read a 2GB file and put in a arraylist and then sort it? assuming memory constraint