1.问题描述
Eclipse中运行代码,出现如下警告。
Description / Resource / Path / Location / Type
Type safety: Unchecked cast from Object[] to E[] SqStackClass.java /SqStackClass/src line 14 Java Problem
2.解决办法
在SqStackClass.java文件开头添加@SuppressWarnings("unchecked")
3.Java顺序栈判断括号是否配对算法的源码展示(两个类)
3.1 第一个类:SqStackClass类
//import java.lang.*;
//import java.util.Comparator;
@SuppressWarnings("unchecked")
public class SqStackClass<E>
{
final int initcapacity=10; //顺序栈的初始容量(常量)
private int capacity; //存放顺序栈的容量
private E[] data; //存放顺序栈中元素
private int top; //存放栈顶指针
public SqStackClass() //构造方法,实现data和size的初始化
{
data = (E[])new Object[initcapacity]; //强制转换为E类型数组
capacity=initcapacity;
top=-1;
}
private void updatecapacity(int newcapacity) //改变顺序栈的容量为newcapacity
{
E[] newdata = (E[])new Object[newcapacity];
for (int i=0;i<top;i++) //复制原来的元素
newdata[i]=data[i];
capacity=newcapacity; //设置新容量
data=newdata; //仍由data标识数组
}
//栈的基本运算算法
public boolean empty() //判断栈是否为空
{
return top==-1;
}
public void push(E e) //元素e进栈
{
if (top==capacity-1) //顺序栈空间满时倍增容量
updatecapacity(2*(top+1));
top++; //栈顶指针增1
data[top]=e;
}
public E pop() //出栈操作
{
if (empty())
throw new IllegalArgumentException("栈空");
E e=(E)data[top];
top--;
if (top+1>initcapacity && top+1==capacity/4) //满足条件则容量减半
updatecapacity(capacity/2);
return e;
}
public E peek() //取栈顶元素操作
{
if (empty())
throw new IllegalArgumentException("栈空");
return (E)data[top];
}
public String toString() //将栈转换为字符串,不是基本运算,仅仅调试用
{
String ans="";
for (int i=0;i<=top;i++)
ans+=data[i].toString()+" ";
return ans;
}
}
3.2 第二个类:Exam3_4类
public class Exam3_4
{
public static boolean isMatch(String str) //例3.4的算法
{
int i=0;
char e;
SqStackClass<Character> st=new SqStackClass<Character>(); //建立一个顺序栈
while (i<str.length())
{
e=str.charAt(i);
if (e=='(' || e=='[' || e=='{')
st.push(e); //将左括号进栈
else
{ if (e==')')
{ if (st.empty()) return false; //栈空返回false
if (st.peek()!='(') return false; //栈顶不是匹配的'('返回false
st.pop();
}
if (e==']')
{ if (st.empty()) return false; //栈空返回false
if (st.peek()!='[') return false; //栈顶不是匹配的'['返回false
st.pop();
}
if (e=='}')
{ if (st.empty()) return false; //栈空返回false
if (st.peek()!='{') return false; //栈顶不是匹配的'{'返回false
st.pop();
}
}
i++; //继续遍历str
}
if (st.empty())
return true; //栈空返回true
else
return false; //栈不空返回false
}
public static void main(String[] args)
{
System.out.println("测试1");
String str="([)]";
if (isMatch(str))
System.out.println(str+"中括号是匹配的");
else
System.out.println(str+"中括号不匹配");
System.out.println("测试2");
str="([])";
if (isMatch(str))
System.out.println(str+"中括号是匹配的");
else
System.out.println(str+"中括号不匹配");
}
}
4.运行结果展示
测试1
([)]中括号不匹配
测试2
([])中括号是匹配的
5.创建工程和类的详情( *.java--------> *.class)
6. 如果已经有源码,如何通过命令行输出展示???
(1)javac -encoding utf8 Exam3_4.java
(2)java Exam3_4
Linux下为UTF-8编码,javac编译gbk编码的java文件时,容易出现“错误: 编码UTF8的不可映射字符”
解决方法是添加encoding 参数:javac -encoding gbk xxx.java
Windows下为GBK编码,javac编译utf-8编码的java文件时,容易出现“错误: 编码GBK的不可映射字符”
解决方法是添加encoding 参数:javac -encoding utf8 xxx.java