I've created a Dataset class used to store and manipulate a dataset. A different class, called Dataset Iris, extends Dataset because Dataset is Principal class where every different datasets (iris and so on) extends it because they have a their feature and a different methods to load it(I can load from a file .txt, .data or database and so on...).
My actually code is this and run, but my teacher tells to me that I should apply "Decorator" design pattern to solve it, but looking the Decorator UML I don't think it because I haven't the "Concrete component" (I can create . What do you think about it? Is a Decorator design pattern or other (like template methods)?
Dataset
public class Dataset
{
private int nFeature;
private int nRecord;
private ArrayList<Integer> featureUsed;
private String nomeDataset;
//public double Mat [][];
private ArrayList<ArrayList<Double>> Mat;
public double Distanza(int i, ArrayList<Double> centroide)
{
double Sum=0;
for(int j=0; j<nFeature; j++)
Sum+=Math.pow((centroide.get(j) - Mat.get(j).get(i)), 2);
return Math.sqrt(Sum);
}
public double getCell(int i, int j)
{
return Mat.get(j).get(i);
}
public void initMat()
{
Mat = new ArrayList<ArrayList<Double>>();
featureUsed = new ArrayList<Integer>();
for(int i=0; i< nFeature; i++)
{
Mat.add(new ArrayList<Double>());
featureUsed.add(i);
}
}
public void writeDataset()
{
for(int i=0; i< nRecord; i++)
{
for(int j=0; j < nFeature; j++)
{
System.out.print( Mat.get(j).get(i)+ " ");
}
System.out.println("\n");
}
}
public ArrayList<Double> getRecord(int i_r)
{
ArrayList<Double> record = new ArrayList<Double>();
for(int i=0; i<nFeature; i++)
record.add( Mat.get(i).get(i_r));
return record;
}
public Dataset(int nFeature, String Nome)
{
setnFeature(4);
setNomeDataset(Nome);
initMat();
}
public Dataset(ArrayList<ArrayList<Double>> MatInput, ArrayList<Integer> featureSelected, int nRecord)
{
Mat = new ArrayList<ArrayList<Double>>();
this.featureUsate = new ArrayList<Integer>(featureSelected);
this.nRecord = nRecord;
this.setnFeature(featureSelected.size());
for(int i=0; i<featureSelected.size(); i++)
setCol( MatInput.get( featureSelected.get(i)));
}
public Dataset() {
// TODO Auto-generated constructor stub
}
public void setCol( ArrayList<Double> colVal)
{
this.Mat.add(colVal);
}
public ArrayList<ArrayList<Double>> getMat()
{
return this.Mat;
}
public int getnFeature() {
return this.nFeature;
}
public int getnRecord() {
return this.nRecord;
}
public void setnFeature(int nFeature)
{
this.nFeature = nFeature;
return;
}
public void setnRecord(int nRecord) {
this.nRecord=nRecord;
return;
}
public void setTable(int Colonna, Double Valore)
{
Mat.get(Colonna).add(Valore);
}
public String getNomeDataset() {
return this.nomeDataset;
}
public void setNomeDataset(String nomeDataset) {
this.nomeDataset = new String(nomeDataset);
}
public double[][] toMatrix()
{
double[][] matrix = new double[this.getnRecord()][this.getnFeature()];
for(int i=0; i< nRecord; i++)
{
for(int j=0; j < nFeature; j++)
{
matrix[i][j] = Mat.get(j).get(i);
}
}
return matrix;
}
public ArrayList<Integer> getFeatureUsed()
{return this.featureUsed;}
}
DatasetIris
public class DatasetIris extends Dataset
{
private String[] nomiFeature = {"Petal Length",
"Petal Width",
"Sepal Length",
"Sepal Width"
};
public DatasetIris(String NomeFile) throws IOException
{
super(4,NomeFile);
super.setnRecord( CaricaDataset(NomeFile) );
}
// Other DatasetIris with their load (database or other type of files)?
protected int loadDataset(String pathFile) throws IOException
{
int iRecord = 0;
BufferedReader bufferLetto = null;
String line = "";
String cvsSplitBy = ",";
try {
bufferLetto = new BufferedReader(new FileReader(pathFile));
while ((line = bufferLetto.readLine()) != null)
{
if (line.length() > 0)
{
String[] cell = line.split(cvsSplitBy);
this.addRow(cell);
iRecord++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferLetto != null) {
try {
bufferLetto.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return iRecord;
}
// New File.data to Mat
public void addRow(Object cell[])
{
for(int i=0; i<getnFeature(); i++)
super.setTable(i, Double.parseDouble(cell[i].toString()));
}
}
Related
I have this class:
package metodo_java8_moderno;
import java.util.ArrayList;
import java.util.List;
public class SingleThreadClass {
public List<Object> editAndAdd(List<List<Long>> matrix){
Long limit = (long) matrix.get(0).size()*matrix.size()/2;
List<Long> numbers = new ArrayList<>();
for(int i=0; i<matrix.get(0).size(); i++){
for(int j=0; j<matrix.size(); j++){
if(matrix.get(j).get(i).longValue() <= limit){
numbers.add(matrix.get(j).get(i));
matrix.get(j).set(i,null);
}
}
}
List<Object> objectList = new ArrayList<>();
objectList.add(matrix);
objectList.add(numbers);
return objectList;
}
}
I want to parallel only the following piece by exploiting all the cores of my CPU:
for(int j=0; j<matrix.size(); j++){
if(matrix.get(j).get(i).longValue() <= limit){
numbers.add(matrix.get(j).get(i));
matrix.get(j).set(i,null);
}
}
I get an error and I believe it is due to the sharing of objects between different threads.
I post all the code of my work:
ElementMutator.java
package metodo_java8_moderno;
#FunctionalInterface
public interface ElementMutator<T> {
void apply(int i);
}
ForkJoinListMutator.java
package metodo_java8_moderno;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class ForkJoinListMutator {
public static final int DEFAULT_SEQ_THRESHOLD = 10000;
private static final ForkJoinListMutator defaultInstance = new ForkJoinListMutator(ForkJoinPool.commonPool());
private final ForkJoinPool forkJoinPool;
public ForkJoinListMutator(ForkJoinPool forkJoinPool) {
this.forkJoinPool = forkJoinPool;
}
public static ForkJoinListMutator getDefault() {
return defaultInstance;
}
public <T> void mutate(List<T> list, ElementMutator<T> mutator) {
mutate(list, DEFAULT_SEQ_THRESHOLD, mutator);
}
public <T> void mutate(List<T> list, int seqThreshold, ElementMutator<T> mutator) {
MutateTask<T> mainTask = new MutateTask<>(list, seqThreshold, mutator);
forkJoinPool.invoke(mainTask);
}
private static class MutateTask<T> extends RecursiveAction {
private final List<T> list;
private final int start;
private final int end;
private final int seqThreshold;
private final ElementMutator<T> mutator;
public MutateTask(List<T> list, int seqThreshold, ElementMutator<T> mutator) {
this(list, 0, list.size(), seqThreshold, mutator);
}
public MutateTask(List<T> list, int start, int end, int seqThreshold, ElementMutator<T> mutator) {
this.list = list;
this.start = start;
this.end = end;
this.seqThreshold = seqThreshold;
this.mutator = mutator;
}
#Override
protected void compute() {
final int length = end - start;
if (length <= seqThreshold) {
computeSequentially();
} else {
MutateTask<T> leftTask = new MutateTask<>(list, start, start+length/2, seqThreshold, mutator);
leftTask.fork();
leftTask.join();
MutateTask<T> rightTask = new MutateTask<>(list, start+length/2, end, seqThreshold, mutator);
rightTask.compute();
}
}
private void computeSequentially() {
for (int i = start; i < end; i++) {
mutator.apply(i);
}
}
}
}
ForkJoinListMutatorExample.java
package metodo_java8_moderno;
import java.util.List;
public class ForkJoinListMutatorExample {
public static void main(String args[]) {
GenerateMatrix generateMatrix = new GenerateMatrix();
List<List<Long>> matrix = generateMatrix.generate(3,4);
System.out.println(matrix);
long t1 = System.nanoTime();
SingleThreadClass singleThreadClass = new SingleThreadClass();
List<Object> output = singleThreadClass.editAndAdd(matrix);
long t2 = System.nanoTime();
System.out.println("Time taken single thread process: " + (t2-t1)/100000000);
List<List<Long>> newMatrix = (List<List<Long>>) output.get(0);
List<Long> numbers = (List<Long>) output.get(1);
System.out.println(newMatrix);
System.out.println(numbers);
t1 = System.nanoTime();
MultiThreadClass multiThreadClass = new MultiThreadClass();
output = multiThreadClass.editAndAdd(matrix);
t2 = System.nanoTime();
System.out.println("Time taken multi thread process: " + (t2-t1)/100000000);
List<List<Long>> newMatrix2 = (List<List<Long>>) output.get(0);
List<Long> numbers2 = (List<Long>) output.get(1);
System.out.println(newMatrix2);
System.out.println(numbers2);
}
}
GenerateMatrix.java
package metodo_java8_moderno;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GenerateMatrix {
public List<List<Long>> generate(int columns, int rows){
List<List<Long>> matrix = new ArrayList<>();
List<Long> row;
Random randomGenerator = new Random();
for(int i=0; i<rows; i++){
row = new ArrayList<>();
for(int j=0; j<columns; j++){
row.add((long) randomGenerator.nextInt(columns*rows+1));
}
matrix.add(row);
}
return matrix;
}
}
MultiThreadClass.java
package metodo_java8_moderno;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MultiThreadClass {
private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
public List<List<Long>> matrix;
public void setMatrix(List<List<Long>> matrix) {
reentrantReadWriteLock.writeLock().lock();
try {
this.matrix = matrix;
} catch (Exception e){
this.matrix = null;
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
public List<List<Long>> getMatrix() {
reentrantReadWriteLock.readLock().lock();
List<List<Long>> matrix;
try {
matrix = this.matrix;
} catch (Exception e){
matrix = null;
} finally {
reentrantReadWriteLock.readLock().unlock();
}
return matrix;
}
public int i;
public void setI(int i) {
reentrantReadWriteLock.writeLock().lock();
try {
this.i = i;
} catch (Exception e){
this.i = -1;
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
public int getI() {
reentrantReadWriteLock.readLock().lock();
int i;
try {
i = this.i;
} catch (Exception e){
i = -1;
} finally {
reentrantReadWriteLock.readLock().unlock();
}
return i;
}
public List<Long> numbers;
public void setNumbers(List<Long> numbers) {
reentrantReadWriteLock.writeLock().lock();
try {
this.numbers = numbers;
} catch (Exception e){
this.numbers = null;
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
public List<Long> getNumbers() {
reentrantReadWriteLock.readLock().lock();
List<Long> numbers;
try {
numbers = this.numbers;
} catch (Exception e){
numbers = null;
} finally {
reentrantReadWriteLock.readLock().unlock();
}
return numbers;
}
public Long limit;
public void setLimit(Long limit) {
reentrantReadWriteLock.writeLock().lock();
try {
this.limit = limit;
} catch (Exception e){
this.limit = null;
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
public Long getLimit() {
reentrantReadWriteLock.readLock().lock();
Long limit;
try {
limit = this.limit;
} catch (Exception e){
limit = null;
} finally {
reentrantReadWriteLock.readLock().unlock();
}
return limit;
}
public List<Object> editAndAdd(List<List<Long>> matrix){
this.matrix = matrix;
this.limit = (long) this.matrix.get(0).size()*this.matrix.size()/2;
this.numbers = new ArrayList<>();
int core = Runtime.getRuntime().availableProcessors();
for(int i=0; i<this.matrix.get(0).size(); i++){
this.i = i;
ForkJoinListMutator listMutator = ForkJoinListMutator.getDefault();
listMutator.mutate(this.matrix,Math.max(1,this.matrix.size()/(core*1+1)),(j) -> parallelFor(j));
}
List<Object> objectList = new ArrayList<>();
objectList.add(this.matrix);
objectList.add(this.numbers);
return objectList;
}
public void parallelFor(int j){
try{
List<List<Long>> matrix = getMatrix();
int i = getI();
List<Long> numbers = getNumbers();
Long limit = getLimit();
if(matrix.get(j).get(i).longValue() <= limit){
numbers.add(matrix.get(j).get(i));
matrix.get(j).set(i,null);
}
setMatrix(matrix);
setI(i);
setNumbers(numbers);
setLimit(limit);
//System.out.println(">> "+this.matrix);
//System.out.println(">> "+this.numbers);
}catch (Exception e){
System.out.println("Errore!");
System.out.println(e.getMessage());
System.out.println(e.getCause());
}
}
}
SingleThreadClass.java
package metodo_java8_moderno;
import java.util.ArrayList;
import java.util.List;
public class SingleThreadClass {
public List<Object> editAndAdd(List<List<Long>> matrix){
Long limit = (long) matrix.get(0).size()*matrix.size()/2;
List<Long> numbers = new ArrayList<>();
for(int i=0; i<matrix.get(0).size(); i++){
for(int j=0; j<matrix.size(); j++){
if(matrix.get(j).get(i).longValue() <= limit){
numbers.add(matrix.get(j).get(i));
matrix.get(j).set(i,null);
}
}
}
List<Object> objectList = new ArrayList<>();
objectList.add(matrix);
objectList.add(numbers);
return objectList;
}
}
I have a graph that contains objects of type GraphNodes. These nodes contain an object City that has properties if It's infected or not. I want to loop through all the nodes and check if a city is infected or not. I have a generic method getInfo which returns an object of type E in my case City. But when i try to chain another method or to get property i can't see them as if they are not available. All the classes in the code are from college so i can't add/remove methods. I've tried with foreach but I still can't get the methods.
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.LinkedList;
class City {
String osnovna_granka;
boolean zarazen;
City(String osnovna_granka, boolean zarazen) {
this.osnovna_granka = osnovna_granka;
this.zarazen = zarazen;
}
#Override
public String toString() {
if (zarazen == true) {
return osnovna_granka + " zarazen";
} else {
return osnovna_granka + " nezarazen";
}
}
}
class Graph {
int num_nodes;
GraphNode<City> adjList[];
#SuppressWarnings("unchecked")
public Graph(int num_nodes) {
this.num_nodes = num_nodes;
adjList = (GraphNode<City>[]) new GraphNode[num_nodes];
}
int adjacent(int x, int y) {
// proveruva dali ima vrska od jazelot so
// indeks x do jazelot so indeks y
return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
}
void addEdge(int x, int y) {
// dodava vrska od jazelot so indeks x do jazelot so indeks y
if (!adjList[x].containsNeighbor(adjList[y])) {
adjList[x].addNeighbor(adjList[y]);
}
}
void deleteEdge(int x, int y) {
adjList[x].removeNeighbor(adjList[y]);
}
#Override
public String toString() {
String ret = new String();
for (int i = 0; i < this.num_nodes; i++) {
ret += i + ": " + adjList[i] + "\n";
}
return ret;
}
}
class GraphNode<E> {
private int index;//index (reden broj) na temeto vo grafot
private E info;
private LinkedList<GraphNode<E>> neighbors;
public GraphNode(int index, E info) {
this.index = index;
this.info = info;
neighbors = new LinkedList<GraphNode<E>>();
}
boolean containsNeighbor(GraphNode<E> o) {
return neighbors.contains(o);
}
void addNeighbor(GraphNode<E> o) {
neighbors.add(o);
}
void removeNeighbor(GraphNode<E> o) {
if (neighbors.contains(o)) {
neighbors.remove(o);
}
}
#Override
public String toString() {
String ret = "INFO:" + info + " SOSEDI:";
for (int i = 0; i < neighbors.size(); i++) {
ret += neighbors.get(i).info + " ";
}
return ret;
}
#Override
public boolean equals(Object obj) {
#SuppressWarnings("unchecked")
GraphNode<E> pom = (GraphNode<E>) obj;
return (pom.info.equals(this.info));
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public E getInfo() {
return info;
}
public void setInfo(E info) {
this.info = info;
}
public LinkedList<GraphNode<E>> getNeighbors() {
return neighbors;
}
public void setNeighbors(LinkedList<GraphNode<E>> neighbors) {
this.neighbors = neighbors;
}
}
public class Main {
public static void main(String[] args) throws Exception {
int i, j, k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Graph g = new Graph(N);
for (i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
st.nextToken();
String osnovna_granka = st.nextToken();
String str_zarazen = st.nextToken();
if (str_zarazen.equals("zarazen")) {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, true));
} else {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, false));
}
}
int M = Integer.parseInt(br.readLine());
for (i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
g.addEdge(a, b);
g.addEdge(b, a);
}
br.close();
Stack<GraphNode> stack = new Stack<>();
int counter = 0;
// vasiot kod ovde;
for(GraphNode gn: g.adjList) {
gn.getInfo().// Here the properties of City should show up
}
}
}
GraphNode is a generic type and you have not specified the type, the IDE cannot infer the type so no methods can be suggested. in the for loop you need to specify the type of the GraphNode.
for(GraphNode<City> gn: g.adjList)
In this code I Got Error ArrayoutofBoundException and NullPointerException in the ml.getV() method
This is my matrix class
public class Matrix {
private double [][] V = null;
// public members
public static int RowsOfVMatrix = 9219;
public static int ColsOfVMatrix = 5;
public static int ROW_INCREASE = 20;
public double[][] getV() {
return V;
}
public void setV(double[][] v) {
V = v;
}
public static int getRowsOfVMatrix() {
return RowsOfVMatrix;
}
public static void setRowsOfVMatrix(int rowsOfVMatrix) {
RowsOfVMatrix = rowsOfVMatrix;
}
public static int getColsOfVMatrix() {
return ColsOfVMatrix;
}
public static void setColsOfVMatrix(int colsOfVMatrix) {
ColsOfVMatrix = colsOfVMatrix;
}
public static int getROW_INCREASE() {
return ROW_INCREASE;
}
public static void setROW_INCREASE(int rOW_INCREASE) {
ROW_INCREASE = rOW_INCREASE;
}
public Matrix(){
V = new double[Matrix.RowsOfVMatrix][Matrix.ColsOfVMatrix];
}
public Matrix(int rowsSize, int colSize){
Matrix.RowsOfVMatrix = rowsSize;
Matrix.ColsOfVMatrix = colSize;
V = new double[Matrix.RowsOfVMatrix][Matrix.ColsOfVMatrix];
}
public Matrix(Matrix m){
V = new double[Matrix.RowsOfVMatrix][Matrix.ColsOfVMatrix];
for (int i = 0; i < Matrix.RowsOfVMatrix; i++) {
for (int j = 0; j < Matrix.ColsOfVMatrix; j++) {
this.V[i][j] = m.V[i][j];
}
}
}
I Tried this code store ArrayList in Matrix using the following code
public static List<Matrix> readFromFileGetMatrixList(String filename)
throws IOException {
List<Matrix> ml = new ArrayList<Matrix>();
Matrix m = null;
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String lineContent;
int matrixNum = 0;
while ((lineContent = br.readLine()) != null) {
if (lineContent.contains("#")) {
matrixNum++;
}
}
matrixNum--;// the last one may be incomplete,so remove it from list
br.close();
fr.close();
fr = new FileReader(filename);
br = new BufferedReader(fr);
int matrixRow_index = 0;
int matrixCount = 0;
while ((lineContent = br.readLine()) != null) {
if (lineContent.contains("#")) {
if (matrixCount > 0) {
ml.add(m);
matrixRow_index = 0;
}
if (matrixCount == matrixNum)
break;
m = new Matrix();
continue;
}
if (lineContent.equals("")) {
matrixCount++;
continue;
}
String[] str = lineContent.split("\t");
for (int j = 0; j < str.length; j++) {
m.getV()[matrixRow_index][j] = Double.parseDouble(str[j]); //Null pointer Exception
}
matrixRow_index++;
}
return ml;
}
This is my Text file sample
0 qid:1 1:1.000000 2:0.693147 3:0.166667 #docid = 285257 0 qid:1
1:1.000000 2:0.693147 3:0.166667 #docid = 285285 0 qid:1 1:1.000000
2:0.693147 3:0.166667 #docid = 285289 0 qid:1 1:1.000000 2:0.693147
3:0.166667 #docid = 285245
In above Code I am getting ArrayBoundofIndexError
I'm working on an exercise and I'm running into something. The following code gives me a stackoverflow error, but I have no idea why because my code should stop.
class Options {
private int amount;
private ArrayList<Integer> pieces;
public void execute() {
pieces = new ArrayList<Integer>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
amount = pieces.size();
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return;
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
It only prints the first output (555).
Thanks.
Add a return to end your recursion
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return; // <-- like so.
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
or put the loop in an else like
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
Edit
static class Options {
private List<Integer> pieces;
public void execute() {
pieces = new ArrayList<>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if (current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for (int i = current.length(); i < pieces.size(); i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
}
public static void main(String[] args) {
Options o = new Options();
o.execute();
System.out.println(o.pieces);
}
Output is
523
[5, 2, 3]
SaveData() and deleteData() are in my studentList class. I'm trying to call them in my UI but they are not working as expected.
I do have a Student class too. Any good idea?
// This is in my UI for my Save and delete button
//add actionListener to SaveData
saveData.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
theList.saveData();
}
});
//add actionListener to DeleteData
deleteData.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
theList.deleteData();
}
});
//saveData()in the StudentList Class
public void saveData() {
try {
FileOutputStream fileOut = new FileOutputStream("StudentData.dat");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeInt(numberOfStudents);
writeStudentsToFile(out);
out.close();
fileOut.close();
} catch ( IOException i ) {
i.printStackTrace();
}
}
public void writeStudentsToFile(ObjectOutputStream out) throws IOException {
for ( int i = 0; i < numberOfStudents; i++ ) {
out.writeObject(studentListArray[i]);
}
}
//deletData() in the StudentList Class
public Student[] deleteData (String firstName)
{
for(int i = 0; i<studentListArray.length; i++)
{
if(studentListArray[i].getFirstName().equals(firstName))
{
numberOfStudents++;
}
}
Student[] studentNewListArray = new Student[studentListArray.length-numberOfStudents];
for(int i = 0; i<studentNewListArray.length; i++)
{
if(studentListArray[i].getFirstName().equals(firstName)|| studentNewListArray[i].getFirstName().equals(null))
{
studentNewListArray[i] = studentListArray[i+1];
studentListArray[i+1] = null;
}
else
{
studentNewListArray[i] = studentListArray[i] ;
}
}
return studentNewListArray;
}
For deletign do something like this ...
public Student[] deleteData (String firstName) {
for(int counter=0;counter< studentListArray.length;counter++){
if(studentListArray[counter].getFirstName().equals(firstName)){
for(int counter1= counter;counter< studentListArray.length-1;counter1++){
studentListArray[counter1]=studentListArray[counter1 +1];
}
studentListArray[counter1+1]=null;
break;
}
}
}