Sie sind auf Seite 1von 11

CSC1022RevisionNotes

ArrayStack

ProblemDescription:
Howtoimplementstack?
Solution:
Followingexampleshowshowtoimplementstackbycreatinguserdefinedpush()
methodforenteringelementsandpop()methodforretrivingelementsfromthestack.
publicclassMyStack{
privateintmaxSize
privatelong[]stackArray
privateinttop
publicMyStack(ints){
maxSize=s
stackArray=newlong[maxSize]
top=1
}
publicvoidpush(longj){
stackArray[++top]=j
}
publiclongpop(){
returnstackArray[top]
}
publiclongpeek(){
returnstackArray[top]
}
publicbooleanisEmpty(){
return(top==1)
}
publicbooleanisFull(){
return(top==maxSize1)
}
publicstaticvoidmain(String[]args){
MyStacktheStack=newMyStack(10)
theStack.push(10)
theStack.push(20)
theStack.push(30)
theStack.push(40)
theStack.push(50)
while(!theStack.isEmpty()){
longvalue=theStack.pop()
System.out.print(value)
System.out.print("")
}
System.out.println("")
}
}
Result:
Theabovecodesamplewillproducethefollowingresult.
5040302010

Queue
public static void main(String[] args) {
Queue<Integer> myQ=new LinkedList<Integer>();
myQ.add(1);
myQ.add(6);
myQ.add(3);
System.out.println(myQ); //1 6 3
int first=myQ.poll();// retrieve and remove the first element
System.out.println(first);//1
System.out.println(myQ);//6 3 }


CompareTo
publicclassTest{

publicstaticvoidmain(Stringargs[]){
Stringstr1="Stringsareimmutable"
Stringstr2="Stringsareimmutable"
Stringstr3="Integersarenotimmutable"

intresult=str1.compareTo(str2)
System.out.println(result)

result=str2.compareTo(str3)
System.out.println(result)

result=str3.compareTo(str1)
System.out.println(result)
}
}

hashCode
1) If two objects are equal by equals() method then there hashcode returned by hashCode()
method must be same.

2) Whenever hashCode() mehtod is invoked on the same object more than once within single
execution of application, hashCode() must return same integer provided no information or fields
used in equals and hashcode is modified. This integer is not required to be same during multiple
execution of application though.

3) If two objects are not equals by equals() method it is not require that there hashcode must be
different. Though its always good practice to return different hashCode for unequal object.
Different hashCode for distinct object can improve performance of hashmap or hashtable by
reducing collision.

Equals
publicbooleanequals(Objectrhs){
//Reflexivity
if(this==rhs)returntrue
//nonnullity
if(!(rhsinstanceofPerson))returnfalse
//consistency
Personp=(person)rhs
returnage==p.age&&(name==null?p.name==null:name.equals(p.name))
}

MutableandImmutable
MutableObjects:Whenyouhaveareferencetoaninstanceofanobject,thecontentsofthat
instancecanbealtered
ImmutableObjects:Whenyouhaveareferencetoaninstanceofanobject,thecontentsofthat
instancecannotbealtered

Immutablemeansthatoncetheconstructorforanobjecthascompletedexecutionthatinstance
can'tbealtered.
Thisisusefulasitmeansyoucanpassreferencestotheobjectaround,withoutworryingthat
someoneelseisgoingtochangeitscontents.Especiallywhendealingwithconcurrency,there
arenolockingissueswithobjectsthatneverchange
e.g.
class final Foo {
private final String myvar;

public Foo(final String initialValue) {
this.myvar = initialValue;
}

public String getValue() {
return this.myvar;
}
}

SampleCode:
Encryption:
importjava.io.File
importjava.io.IOException
importjavax.swing.JFileChooser
importjavax.swing.JOptionPane

publicclassEncrypterTest
{

/**
*@paramargs
*/
publicstaticvoidmain(String[]args)
{
try{
JFileChooserchooser=newJFileChooser()
if(chooser.showOpenDialog(null)!=JFileChooser.APPROVE_OPTION){
System.exit(0)//TODOAutogeneratedmethodstub
}
FileinFile=chooser.getSelectedFile()
if(chooser.showSaveDialog(null)!=JFileChooser.APPROVE_OPTION){
System.exit(0)
}
FileoutFile=chooser.getSelectedFile()
Stringinput=JOptionPane.showInputDialog("Key")
intkey=Integer.parseInt(input)
Encryptorcrypt=newEncryptor(key)
crypt.encryptFile(inFile,outFile)
}
catch(NumberFormatExceptione){
System.out.println("Keymustbeaninteger:"+e)
}
catch(IOExceptione){
System.out.println("Errorprocessingfile:"+e)
}

ScannerClass(Everythingyoucouldwant)
MethodSummary
ModifierandType MethodandDescription
void close()
Closesthisscanner.
Pattern delimiter()
ReturnsthePatternthisScanneriscurrentlyusingtomatchdelimiters.
String findInLine(Patternpattern)
Attemptstofindthenextoccurrenceofthespecifiedpatternignoringdelimiters.
String findInLine(Stringpattern)
Attemptstofindthenextoccurrenceofapatternconstructedfromthespecified
string,ignoringdelimiters.
String findWithinHorizon(Patternpattern,inthorizon)
Attemptstofindthenextoccurrenceofthespecifiedpattern.
String findWithinHorizon(Stringpattern,inthorizon)
Attemptstofindthenextoccurrenceofapatternconstructedfromthespecified
string,ignoringdelimiters.
boolean hasNext()
Returnstrueifthisscannerhasanothertokeninitsinput.
boolean hasNext(Patternpattern)
Returnstrueifthenextcompletetokenmatchesthespecifiedpattern.
boolean hasNext(Stringpattern)
Returnstrueifthenexttokenmatchesthepatternconstructedfromthe
specifiedstring.
boolean hasNextBigDecimal()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
BigDecimalusingthenextBigDecimal()method.
boolean hasNextBigInteger()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
BigIntegerinthedefaultradixusingthenextBigInteger()method.
boolean hasNextBigInteger(intradix)
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
BigIntegerinthespecifiedradixusingthenextBigInteger()method.
boolean hasNextBoolean()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
booleanvalueusingacaseinsensitivepatterncreatedfromthestring
"true|false".
boolean hasNextByte()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasabyte
valueinthedefaultradixusingthenextByte()method.
boolean hasNextByte(intradix)
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasabyte
valueinthespecifiedradixusingthenextByte()method.
boolean hasNextDouble()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
doublevalueusingthenextDouble()method.
boolean hasNextFloat()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasafloat
valueusingthenextFloat()method.
boolean hasNextInt()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasanint
valueinthedefaultradixusingthenextInt()method.
boolean hasNextInt(intradix)
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasanint
valueinthespecifiedradixusingthenextInt()method.
boolean hasNextLine()
Returnstrueifthereisanotherlineintheinputofthisscanner.
boolean hasNextLong()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasalong
valueinthedefaultradixusingthenextLong()method.
boolean hasNextLong(intradix)
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasalong
valueinthespecifiedradixusingthenextLong()method.
boolean hasNextShort()
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
shortvalueinthedefaultradixusingthenextShort()method.
boolean hasNextShort(intradix)
Returnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasa
shortvalueinthespecifiedradixusingthenextShort()method.
IOException ioException()
ReturnstheIOExceptionlastthrownbythisScanner'sunderlying
Readable.
Locale locale()
Returnsthisscanner'slocale.
MatchResult match()
Returnsthematchresultofthelastscanningoperationperformedbythis
scanner.
String next()
Findsandreturnsthenextcompletetokenfromthisscanner.
String next(Patternpattern)
Returnsthenexttokenifitmatchesthespecifiedpattern.
String next(Stringpattern)
Returnsthenexttokenifitmatchesthepatternconstructedfromthespecified
string.
BigDecimal nextBigDecimal()
ScansthenexttokenoftheinputasaBigDecimal.
BigInteger nextBigInteger()
ScansthenexttokenoftheinputasaBigInteger.
BigInteger nextBigInteger(intradix)
ScansthenexttokenoftheinputasaBigInteger.
boolean nextBoolean()
Scansthenexttokenoftheinputintoabooleanvalueandreturnsthatvalue.
byte nextByte()
Scansthenexttokenoftheinputasabyte.
byte nextByte(intradix)
Scansthenexttokenoftheinputasabyte.
double nextDouble()
Scansthenexttokenoftheinputasadouble.
float nextFloat()
Scansthenexttokenoftheinputasafloat.
int nextInt()
Scansthenexttokenoftheinputasanint.
int nextInt(intradix)
Scansthenexttokenoftheinputasanint.
String nextLine()
Advancesthisscannerpastthecurrentlineandreturnstheinputthatwas
skipped.
long nextLong()
Scansthenexttokenoftheinputasalong.
long nextLong(intradix)
Scansthenexttokenoftheinputasalong.
short nextShort()
Scansthenexttokenoftheinputasashort.
short nextShort(intradix)
Scansthenexttokenoftheinputasashort.
int radix()
Returnsthisscanner'sdefaultradix.
void remove()
TheremoveoperationisnotsupportedbythisimplementationofIterator.
Scanner reset()
Resetsthisscanner.
Scanner skip(Patternpattern)
Skipsinputthatmatchesthespecifiedpattern,ignoringdelimiters.
Scanner skip(Stringpattern)
Skipsinputthatmatchesapatternconstructedfromthespecifiedstring.
String toString()
ReturnsthestringrepresentationofthisScanner.
Scanner useDelimiter(Patternpattern)
Setsthisscanner'sdelimitingpatterntothespecifiedpattern.
Scanner useDelimiter(Stringpattern)
Setsthisscanner'sdelimitingpatterntoapatternconstructedfromthespecified
String.
Scanner useLocale(Localelocale)
Setsthisscanner'slocaletothespecifiedlocale.
Scanner useRadix(intradix)
Setsthisscanner'sdefaultradixtothespecifiedradix.

Das könnte Ihnen auch gefallen